Posts on this Category



Angular2 Tutorial: Creating Custom Pipes

Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don’t meet our needs, that’s when we have to create custom pipes. This will be a very quick tutorial in which I’ll give you an example of how you can create your own pipes.

I’m assuming you already have your angular2 project, but if you don’t, just follow the instructions on the official site to create a starter project. Make sure the project is working before you proceed.

As an example I’m going to create a pipe to limit the amount of characters on a string, let’s assume you have limited space on your page and there is no way for you to display the entire text, you’ll just provide the maximum amount of characters and the pipe will take care of the rest, every time you come across this situation you can use this pipe to make the text fit on the space you have available.

Let’s start by creating in our app folder a file called maxLength.pipe.ts, copy/paste the following code into it:

import {Pipe} from 'angular2/core';
 
@Pipe({
    name: 'maxLength'
})
export class MaxLengthPipe {
    transform(val, args) {
        if (val.length > 30){
            return val.substring(0, 30)+'...';    
        }else{
            return val;
        }
    }
}

Perfect, you already have a pipe!! All you had to do was to create a class and put the @Pipe decorator on it, but to make it work we also have to implement the transform function, that’s where we are going to put our logic. In this simple example I’m just checking if my text has a length greater than 30, if it does I’m returning the first 30 characters.

That’s enough for us to be able to use our pipe, open your app.component.ts and paste the following code:

import {Component} from 'angular2/core';
import {MaxLengthPipe} from './maxLength.pipe';
 
@Component({
    selector: 'my-app',
    template: `<p>{{value | maxLength}}</p>`,
    pipes: [MaxLengthPipe]
})
 
export class AppComponent { 
    public value = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel dui '
                  +'at sem placerat dictum dictum placerat est. Mauris pretium mattis nulla '
                  + 'vel suscipit.Vestibulum laoreet congue erat, eget bibendum justarius id';   
}

That’s the simplest possible example, I have a class with just one attribute which will store my text. Note how I used the pipe in the template, I just wrote the name of my variable followed by the pipe name we specified in the @Pipe decorator, which in this case was maxLength.

If you run the project you’ll see that it’s already working, but we can improve it a little bit more, instead of always returning the first 30 characters, we can pass a parameter to the pipe telling how many characters we want. To do that we have to modify our transform function, everywhere we were using the number 30 we have to replace it by args[0], this is how it should look like:

transform(val, args) {
    if (val.length > args[0]){
        return val.substring(0, args[0])+'...';    
    }else{
        return val;
    }
}

Then in the app.component.js you can pass the parameter like this:

{{value | maxLength : 30}}

That’s it!! Hope you enjoyed the tutorial, leave a comment if you have any doubts.

Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns

In this tutorial I’m going to show you one of the datatable solutions available for Angular 2, it’s called ag-Grid and it’s available not only for angular2, but also for other frameworks like Angular 1 and React. It’s a really complete datatable, it has lots of features that I definitely want to explore in other tutorials, but in this one I’ll try to keep it as simple as possible, my goal is to just make it display the data and enable the sorting, filtering and the resizable columns features. Maybe in the future I’ll write a PART 2 of this tutorial explaining how to add some more complex functionality. If you don’t want to use ag-grid take a look at this post.

I’m assuming you already have your Angular 2 project ready, but if you don’t just follow the instructions on this link to set up your environment, it’s really easy and straightforward, all you need to do is to create three configurations files: tsconfig.json, typings.json and package.json, make sure you have all of them before you continue.

Now let’s add the ag-grid to the project, to do that you have to add these two lines to the dependencies list on your package.json:

{
  "dependencies": {
    "ag-grid": "3.3.x",
    "ag-grid-ng2": "3.3.x"
    ...
  },
}

Run npm install to download and install the dependencies, when it completes we’ll be ready to start writing some code!

Open your project folder and create another one inside called app, that’s where we’re going to put all our Angular2 related code. The first file we are going to create on this folder is the app.component.ts, it should contain the following code, just copy and paste it into the file:

import {Component} from 'angular2/core';
import {AgGridNg2} from 'ag-grid-ng2/main';
 
@Component({
    selector: 'my-datatable',
    directives: [AgGridNg2],
    template: `
         <ag-grid-ng2 #agGrid style="height:100%;width:845px" class="ag-fresh"
            [gridOptions]="gridOptions">
         </ag-grid-ng2 >
     `
})
 
export class AppComponent { 
    myRowData = [
        {"name":"Ronald Bowman","country":"China","city":"Lutou","email":"rbowman0@spotify.com"},
        {"name":"Pamela Hill","country":"Russia","city":"Krylovskaya","email":"phill1@symantec.com"},
        {"name":"Robin Andrews","country":"Ukraine","city":"Korop","email":"randrews2@photobucket.com"},
        {"name":"Peter Kim","country":"Mexico","city":"San Jose","email":"pkim3@theatlantic.com"},
        {"name":"Carol Foster","country":"Mexico","city":"El Aguacate","email":"cfoster8@intel.com"},
        {"name":"Jimmy Burke","country":"Indonesia","city":"Banjarsari","email":"jburke9@over-blog.com"},
        {"name":"Jonathan Crawford","country":"Peru","city":"Alca","email":"jcrawforda@deliciousdays.com"},
        {"name":"Donald Montgomery","country":"Poland","city":"Działoszyce","email":"dmontgomeryb@google.com.br"},
        {"name":"Donna Shaw","country":"Japan","city":"Akune","email":"dshawc@chronoengine.com"},
        {"name":"Helen King","country":"United States","city":"Hollywood","email":"hkingd@devhub.com"},
        {"name":"Walter Myers","country":"China","city":"a ndaowa n", "email":"wmyerse@state.tx.us"},
        {"name":" Alice Collins","country":"Papua Nw  Guine a", "city":"Mendi","email":"acollinsf@npr.org"},
        {"name":"Anne Richards","country":"China","city":"Koramlik","email":"arichardsu@vinaora.com"},
        {"name":"Randy Miller","country":"Indonesia","city":"Trenggulunan","email":"rmillerv@oakley.com"},
        {"name":"Phillip Adams","country":"Bahamas","city":"Duncan Town","email":"padamsw@lycos.com"},
        {"name":"Nicholas Allen","country":"Philippines","city":"Bautista","email":"nallenx@aboutads.info"},
        {"name":"Lisa Willis","country":"Thailand","city":"Lat Yao","email":"lwillisy@istockphoto.com"},
        {"name":"Jeffrey Castillo","country":"Indonesia","city":"Karangsari","email":"jcastilloz@washington.edu"},
        {"name":"Michael Carpenter","country":"Colombia","city":"Cali","email":"mcarpenter13@prlog.org"},
        {"name":"Roger Lee","country":"France","city":"Courtaboeuf","email":"rlee14@earthlink.net"},
        {"name":"Steve Wallace","country":"Russia","city":"Novobeysugskaya","email":"swallace15@cisco.com"},
        {"name":"Shirley Patterson","country":"Peru","city":"La Tinguiña","email":"spatterson16@woothemes.com"},
        {"name":"Nancy Ward","country":"Sweden","city":"Båstad","email":"nward17@mapquest.com"}
    ];
 
    columnDefs = [
        {headerName: 'Name', field: "name", width: 200 },
        {headerName: 'Country', field: "country" ,width:180},
        {headerName: 'City', field: "city" ,width:160},
        {headerName: 'e-mail', field: "email" ,width:300}
    ];
 
    gridOptions = [];
 
    constructor() {
        this.gridOptions = {
            rowData: this.myRowData,
            columnDefs: this.columnDefs,
            enableColResize: true,
            enableSorting: true,
            enableFilter: true
        }   
    }
}

There is quite a lot to explain about this code, I’m going to start with the class AppComponent, that’s where we’re going to put all the parameters and configurations that makes our datatable work, we have three variables on this class: myRowData, columnDefs and gridOptions.

myRowData: This variable will store the data to be displayed on the table, for this example I’m just going to use some JSON data I generated, but in a real case scenario you would get the data from your database or a web service.

columnDefs: This one will store an object containing information about every column of our datatable, I’m just using the attributes headerName to define the column title, field to tell which array attribute will be displayed on the column and width to define the size of each column. Although I’m using only three, there are tons of other attributes you could specify here.

gridOptions: This one just wraps everything up and make it available to the component. It’s being initialized empty, but in the constructor I’m setting its value, besides the rowData and columnDefs I’m also specifying the attributes enableColResize, enaleSorting and enableFilter. They will do exactly what their names suggests, enable the columns resize, sorting and filtering features respectively.

Now we can create our component, to be able to use the directive AgGridNg2 we have import it first with the line import {AgGridNg2} from 'ag-grid-ng2/main, after that all you need to do is to pass the gridOptions to the ag-grid-ng2 component on the template.

Before we write the index.html we’re going to need one more ts file to be able to launch our application, on your app folder create the file main.ts and paste the following code into it:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'
 
bootstrap(AppComponent);

Now you can create the index.html file on your project root folder, let’s take a look at the code:

<html>
  <head>
    <title>Datatable</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <link href="node_modules/ag-grid/dist/styles/ag-grid.css" rel="stylesheet" />
    <link href="node_modules/ag-grid/dist/styles/theme-fresh.css" rel="stylesheet" />
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          },        
          lib: {
            format: 'register',
            defaultExtension: 'js'
          },
          'ag-grid-ng2': {
            defaultExtension: "js"
          },
          'ag-grid': {
            defaultExtension: "js"
          }
        },
        map: {
            'ag-grid-ng2': 'node_modules/ag-grid-ng2',
            'ag-grid': 'node_modules/ag-grid'
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <my-datatable>Loading...</my-datatable>
  </body>
</html>

This file will basically be used just to load the necessary scripts and to configure SystemJS to load everything and launch the application. Finally you can use your component here calling it by the selector we specified before: my-datatable.

We’re done!! To run the project open your terminal, navigate to your project folder and run npm start, this should be the result: my-datatable.

Angular 2 Datatable with Sorting, Filtering and Resizable Columns
Angular 2 Datatable with Sorting, Filtering and Resizable Columns

Creating a Live Auction App with Angular 2, Node.js and Socket.IO

Angular 2 Auction App
Angular 2 Auction App

In this tutorial we’re going to build a very cool Live Auction Application, my goal is to demonstrate how Angular 2, Node.js and Socket.io work together, and as everyone knows Angular 2 will soon come out so I thought it would be great to write a tutorial involving it. Of course our app won’t have all the features a real auction app has, this is just an example to demonstrate how to integrate the frameworks I mentioned.

Setting up the Environment

The first step is to configure the environment, let’s get started by creating our Node.js project, I’m going to use express to do it, if you don’t have it open your terminal and run the command npm install express-generator -g to install, then you can create the project with the command expess {project name} (replace {project name} with your actual project name).

Now you have the basic project structure created for you, but we need to make some changes in order add Angular 2 and Socket.io to the project, first open your package.json and paste the following code:

{
  "name": "auction",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "postinstall": "npm run typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
    "typings" : "typings"
  },
   "license": "ISC",
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "angular2": "2.0.0-beta.6",
    "systemjs": "0.19.20",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.14",
    "socket.io":"1.4.5"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^2.0.1",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}

Now create another file called tsconfig.json in the project root folder and put the following into the file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Also in the root folder create the typings.json and copy/paste the following code into it:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim
/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}

Ok, we have now created all the configuration files, but before we continue you have to install the dependencies by running the command npm install on the terminal.

If you open your app.js you’ll see that express has already put some code in there, in order to make it as simple as possible let’s delete the code we don’t need, after the modification your app.js should look like this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
 
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/', routes);
 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
 
module.exports = app;

By default express sets jade as the view engine, we’ve already deleted the lines responsible for that in the app.js, but if you check the folder /views you’ll see some .jade files, you can delete them if you want, later we’re going to place our Angular 2 HTML pages in this folder, but for now you can just create and leave an empty index.html in there.

After getting rid of the .jade files we have to tell Node.js that we want to use our index.html instead, we can do that by changing a little bit the code in the routes/index.js file, just open the file and replace its content with the following code:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

To make sure it’s working run your project with the command npm start then enter the url http://localhost:3000/ in your browser, it should display an empty page, write something in the index.html you created and refresh the page, if it appears on the browser you’ve done everything right! Now we’re ready to actually start writing some code.

Introducing Socket.IO

As we know, an auction app must be real-time, which means that when a user places a bid all the other connected users must instantly see it, that’s where Socket.IO comes in, it allows Node.js to receive and broadcast events to all connected clients, so when a user places a bid Socket.IO will emit an event to the server which will update the product price and broadcast it to the other users.

Now let’s see how that looks like in code, copy the following code and paste bellow the var app = express(); in your app.js:

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
io.set("origins", "*:*");
 
var currentPrice = 99;
 
io.on('connection', function (socket) {
	socket.emit('priceUpdate',currentPrice);
	socket.on('bid', function (data) {
		currentPrice = parseInt(data);
		socket.emit('priceUpdate',currentPrice);
		socket.broadcast.emit('priceUpdate',currentPrice);
	});
});

In the first 5 lines I’m just creating the server that Socket.IO will use to send/receive events, then I’m creating a listener to the connection event which will be emitted every time a user connects (we’ll get to that in a moment), you can use the function io.on(event, callback) to create a listener to any event you want, you just need to pass the event as the fist argument and the callback function as the second, when it receives the event the callback will be executed.

In this case when a user connects I’m immediately emitting the event priceUpdate passing the current price, that’s because at this moment the client-side doesn’t have the current price yet, so that’s the first thing we want to send. After that we have to create a listener to the bid event that will update the price and broadcast to the other users. Note that I’m calling socket.emit() and socket.broadcast.emit(), the first one will return the updated price to the user that triggered the event, and the second will do the same to all the other users.

Writing our First Angular 2 Component

Now that we have our server-side ready we can get started with Angular 2, let’s create a folder called app inside public/javascripts/ on our project, that’s where we’re going to put all our Angular 2 code. Now create a file and name it app.component.ts, then paste the following code into it:

import {Component} from 'angular2/core';
 
@Component({
    selector: 'auction-app',
    templateUrl: 'templates/product.html'
})
 
export class AppComponent {
    price: number = 0.0;
    socket = null;
    bidValue = '';
 
    constructor(){
        this.socket = io('http://localhost:8000');
        this.socket.on('priceUpdate', function(data){
            this.price = data;
        }.bind(this));    
    }
 
    bid(){
        this.socket.emit('bid', this.bidValue);
        this.bidValue = '';
    }
}

When declaring a @Component, you have to pass an object containing two attributes selector and templateUrl (or just template), the selector is the name we’re going to use to call our component, in this case it’s auction-app, and the templateUrl is the HTML implementation, you can put your HTML code directly on the object or you can put it in a separated file like I did.

We also have in this code the AppComponent class, that’s kind of the ‘controller’ of our component, in the constructor I’m connecting to the Socket.IO from the server using the method io('http://localhost:8000'), this will emit the connection event we saw before, then I’m creating a listener to the priceUpdate event, the server will emit it right after the connection, remember? When Angular receives the updated price it will assign it to the price variable. This class also contains the bid() function, it will just emit the bid event passing the bidValue.

I forgot to mention that I created the /template folder inside /views, the problem is that our component doesn’t have access to it, to solve this problem we have to make this folder a static route on our server, open your app.js and add this line:

app.use('/templates', express.static(__dirname + '/views/templates/'));

Now let’s take a look on our template, I’ll not show the full HTML code here, just the lines that interact with our AppComponent class.

<h1>$ {{price}}</h1>	        
<input  [(ngModel)]="bidValue" >
<button (click)="bid()">Place Bid</button>

There is not much to explain here, the syntax resembles a lot the first Angular, our input uses the attribute [(ngModel)] to reference the bidValue variable from our class, and the button uses the (click) to call the function bid().

To be able to launch our application we have to create a file called main.ts on the public/javascripts/ folder, just copy/paste the following into the file:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component.js'
 
bootstrap(AppComponent);

Finally we can write our index.html, you have already created it in the beginning, remember? It’s located on the /views folder, open it and add the following code:

<html>
  <head>
    <title>Live Auction</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script> 
    <script src="scripts/es6-shim/es6-shim.min.js"></script>
    <script src="scripts/systemjs/dist/system-polyfills.js"></script>
    <script src="scripts/angular2/bundles/angular2-polyfills.js"></script>
    <script src="scripts/systemjs/dist/system.src.js"></script>
    <script src="scripts/rxjs/bundles/Rx.js"></script>
    <script src="scripts/angular2/bundles/angular2.dev.js"></script>
    <script src="javascripts/jquery.js"></script>
    <script src="javascripts/bootstrap.min.js"></script>
    <link href="stylesheets/bootstrap.min.css" rel="stylesheet">
    <link href="stylesheets/portfolio-item.css" rel="stylesheet">
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('javascripts/app/main.js')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <auction-app>Loading...</auction-app>
  </body>
</html>

Once again we have to edit the app.js file to be able to load the scripts directly from the node_modules folder, add the following line like we did before:

app.use('/scripts', express.static(__dirname + '/node_modules/'));

This file is pretty simple, we have a script that configures System.js to load our application, and in the body we can call our component by the selector we specified before: auction-app.

Now we’re done!! You can run your application by opening your terminal and running the command npm start, the result should similar to the gif in the beginning of this tutorial.

Just leave a comment if you have any problems, I’ll be glad to help!!

AngularJS Internationalization Example

Today I’m going to give you a very simple example of how to translate a AngularJS page with the module angular-translate. To illustrate how to do that, I’m going to create a login screen with 3 or 4 labels, then I’ll make them available in two different languages: English and French. If you need more languages you just have to follow the same principle.

The first thing we need to do is to provide the texts in both languages to our application, we can easily do that in the module.config function, let’s take a look at the code, this will be our app.js file:

var app = angular.module('angularjs_internationalization',['pascalprecht.translate']);
 
app.config(function($translateProvider) {
  $translateProvider.translations('en_US', {
    TITLE: 'Login Form',
    USERNAME: 'Username',
    PASSWORD: 'Password',
    LOGIN: 'Login'
  });
 
  $translateProvider.translations('fr_CA', {
    TITLE: 'Formulaire de login',
    USERNAME: 'Identifiant',
    PASSWORD: 'Mot de passe',
    LOGIN: 'Connexion'
  });
  $translateProvider.determinePreferredLanguage();
});

I just declared the two languages using the function translations() from the translateProvider service, it receives the language key as the first argument and an object containing the texts as the second, note that related texts have same ID in both objects, it won’t work if you use different IDs. After that I called the function determinePreferredLanguage() which tells AngularJS to choose the most suitable language for each user, you can also pick a language by hand, I’ll tell you how to do that in a moment.

Next, we need to create the HTML page, just copy the following code and paste into your index.html file:

<html ng-app="angularjs_internationalization">
<head>
	<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js" />
	<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.9.0/angular-translate.min.js" />
	<script src="app.js" />
	<link href="style.css" rel="stylesheet" type="text/css"  />
	<title translate>TITLE</title>
</head>
<body>
	<div class="loginpanel">
	  <div class="txt">
	    <input id="user" type="text" placeholder="{{'USERNAME' | translate}}" />
	    <label for="user" class="entypo-user"></label>
	  </div>
	  <div class="txt">
	    <input id="pwd" type="password" placeholder="{{'PASSWORD' | translate}}" />
	    <label for="pwd" class="entypo-lock"></label>
	  </div>
	  <div class="buttons">
	    <input type="button" value="{{'LOGIN' | translate}}" />
	  </div>
	</div>
<span class="resp-info"></span>
</body>
</html>

You don’t need to be concerned about every single line of this code, what matters here is just how we call our texts from the angular module, which is very simple, as you can see in the placeholder attribute of both inputs, you just need to call your text ID followed by the filter translate.

Now if you run you project you should see the page in your browser’s default language:

Login Form in English
Login Form in English

If you want to test the other language as well, instead of calling the determinePreferredLanguage() function at the end of the config() method, you have to call preferredLanguage() passing the language you want:

$translateProvider.preferredLanguage('fr_CA');

And this should be the result:

Login Form Translated
Login Form Translated

That’s it guys! Thanks for reading this tutorial, just leave a comment if you have any problems, I’ll be glad to help!

AngularJS Tutorial: Conditional Render Example

As a web developer I can say that everyone that works with web development, no matter the language, comes across conditional rendering very often (almost every day), it’s pretty much impossible to see a project that doesn’t have a UI component that cannot be shown if a specific condition isn’t true. And that is not different for AngularJS developers, so today we’re going to learn how to do it with AngularJS, this will be a very simple and easy tutorial, if you are just getting started with angularjs this is the right tutorial for you.

So let’s get started, the example I’m going to give consists in an application with a button that will be responsible for showing and hiding a div that contains some content, to make that content visible and invisible we’re going to use conditional rendering, pretty straightforward, right?

We’re going to start by creating the app.js file, here is how it should look like:

var app = angular.module('renderExample',[]);
app.controller('renderExampleController', function($scope){
	$scope.showContent= true;
	$scope.label= 'Hide Text';
 
	$scope.switch = function(){
		if($scope.showContent){
			$scope.showContent= false;
			$scope.label= 'Show Text';
		}else{
			$scope.showContent= true;
			$scope.label= 'Hide Text';			
		}
	}
});

As you can see, I’ve declared two variables in my controller: showContent and label. The first one, as the name suggests, is the condition to render the content, it will only appear on the page when this variable is set to true, and the second one is the text that will appear in the button, when the content is visible the label will be 'Hide Text', and when it’s invisible it’ll be 'Show Text'. Lastly, we have the function switch() which will be called by the button and will be responsible for switching the content visibility by changing the two variables values.

Now the last thing we need to do is to create the index.html file:

<!DOCTYPE html>
<html ng-app="renderExample">
   <head>
      <title>Conditional Render Example</title>
      <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
      <script src="app.js"></script>
   </head>
   <body>
      <div ng-controller="renderExampleController">
         <input type="button" value="{{label}}" ng-click="switch()"/>
         <br />
         <div ng-if="showContent">
            Some content.
         </div>
      </div>
   </body>
</html>

You should be familiar with most of this code, what really matters here is the directive ng-if, this is the directive that controls if the component will be rendered or not, you just need to pass the condition, which in this case is the variable showContent.

That’s it!! Now if you execute your project you should be able to show/hide the text by pressing the button.

Tutorial: Integrating AngularJS with NodeJS

Integrating AngularJS with NodeJS
Integrating AngularJS with NodeJS

I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it’s a very common to see people asking how to integrate both, so this will be a very simple beginner level tutorial in which I’ll give an example to demonstrate how AngularJS and NodeJS can work together.

I’m assuming you have already set your enviroment, so we are going to start by creating our NodeJS project, to do that I’m going to use express, if you don’t have it yet just install via npm with the following command line:

npm install express-generator -g

With express installed simply navigate via terminal to the folder you want your project to be located and execute the command express passing your project name as a parameter, like this:

express myNodeProject

Now that your project is created, you can open it with the text editor of your choice, I’m going to use Sublime Text for this tutorial. When you do it you’ll see that express has already created the basic project structure for you:

Folder Structure
Folder Structure

By default, express uses Jade as the view engine, as you can see in the views folder we already have some jade files, which we are not going use, you can get rid of them later if you want. We’ll need to make some changes here to be able to use angularjs. Let’s begin by opening the file routes/index.js, it contains the following code:

var express = require('express');
var router = express.Router();
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
module.exports = router;

That’s the code responsible for rendering and redirecting to the index.jade file, what we need to do here is to change it a little bit and make it redirect to our angularjs index.html file (which we are going to create in a moment). After the changes the code should look like this:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

Now we need to create our index.html file, I’m going to put it in the views folder with the jade files. This is how my HTML code looks like:

<!DOCTYPE html>
<html ng-app="angularjsNodejsTutorial">
    <head>
        <title>Integrating AngularJS with NodeJS</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="javascripts/app.js" type="text/javascript"></script> <!-- not created yet -->
    </head>
    <body >
        <div ng-controller="myController">
        </div>
    </body>
</html>

In this file you can use not only AngularJS, but any javascript library you want, if you run your project you’ll see that nodejs is already redirecting to this file, you can now create you angularjs module and start writing some angularjs code as usual.

At this point you are already using angular and node in your application, but they are kind of independent from each other, there are no communication between them. To finish up this tutorial I’m going to show how AngularJS can make a request to NodeJS. But before we do that, we need to come back to the index.js file (the one we just modified) and create a function to return some data, which will be called when we make the request from our angularjs controller, just copy the following code and paste it right above the module.exports on your index.js.

router.get('/data', function(req,res){
	res.json([{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}]);
});

What is happening here is that the router.get function is assigning a function to the url ‘/data’, so when the user types ‘/data’ in the browser, node will call this function, which is doing nothing more than returning a json, it could be getting and handling data from the database, but as I want to keep it simple, a static json will do the job.

Now let’s create our app.js file, as you can see in the HTML code, it’s already referenced there. I’m going to put it on the public/javascript folder.

var app = angular.module('angularjsNodejsTutorial',[]);
app.controller('myController', function($scope, $http) {
    $scope.data = [];
    var request = $http.get('/data');    
    request.success(function(data) {
        $scope.data = data;
    });
    request.error(function(data){
        console.log('Error: ' + data);
    });
});

This is also a very straightforward code, I’m using the function $http.get with the argumentet ‘/data’ to make the request, then I’m assigning the result to $scope.data.

Now we just need to modify a little bit our HTML to make it iterate over our data and show it on the screen, just add this to the div with the ng-controller:

<ul ng-repeat="item in data">
	<li>Name: {{item.name}}, City: {{item.city}}</li>
</ul>

That’s it!! Now just run your project by executing npm start on the terminal and you’ll be able to access the application on your browser by typing localhost:3000, if you did everything right you should see a page with the data from our json.

Hope this tutorial was helpful, till the next one!!

Understanding and Creating AngularJS Factories

Factories are very similar to AngularJS Services, lots of people struggle to understand the difference between them, if you are one of those, I ensure you’ll clearly understand the difference after reading this tutorial in which I’ll explain the concepts behind AngularJS services and factories, after that I’ll give you a simple example of how to create a factory.

Let’s start with the services, they are basically objects containing the business logic related to an specific entity or feature of your project, for example: your application will have users, right? These users can probably perform some actions like sign up, log in, log out, etc. You could create a service to group all the user related business logic, it would have these three functions I just mentioned: signin() login() and logout(). If you want more details about services, just click on this link.

Factories are a little bit different, instead of performing actions, factories, as the name suggests, are more appropriate to generate and return objects of an specific type. To make it easier to understand let’s come back to the user example, besides the actions I mentioned above, a user has also attributes, like name, login, password, etc. We could create a factory to generate and return objects with these three attributes, it would be a users factory.

Now let’ me show you how to create factories:

var app = angular.module('factoryExample',[]);
 
app.factory('User', function(){
    return function(name, login, password){
        return {
            name : name,
            login : login,
            password : password
        }
    }
});

This is a very straightforward code, it’s the simplest factory I can create, it returns a function that creates a user object according to the parameters passed to it, now you can inject it on your controller and use it like this:

app.controller('myController', function($scope, User){
	var user1 =  new User('Kate','jhpa','urej2232js');
	console.log(user1.name);
	console.log(user1.login);
	console.log(user1.password);
});

If you run your project you should see the attributes printed on your console.

Now you must be wondering, why didn’t I put the user actions and attributes on the same object instead of creating a service and a factory for it? Well, this was just an example, you could totally do it if you prefer, there is countless ways to do it, it’s up to you to choose the most suitable for your project.

That’s it for today guys!! Leave a comment if you have any doubts or suggestions.
Till next tutorial!!

Tutorial: Creating AngularJS Services

Imagine that you have a project with countless features responsible for performing a huge variety of tasks, if you don’t do as much as you can to organize it, how would the code look like? It would be nearly impossible to maintain this project if everything is mixed together in the code, no one would understand it. To make things easier we make whatever we can to keep our code as readable and clean as possible, and that’s what AngularJS Services are good for.

Let’s suppose your project has a lot of features related to products management, you wouldn’t put that together with the code related to employees management, right? Of course not, they have nothing to do with each other, in this case AngularJS allows you to create a service for products and another one for employees, this way all the business logic would be organized in its appropriate service. If someone in the future needs to develop a new product related feature, he/she will know where to find the business logic related to it.

Now let’s see how that looks like in code, I’m going to create 2 services (productService and employeeService), each one will have it’s specific functions, which of course will be different from each other, the productService will allow us to get information and check the availability of an specific product, as the employeeService will only have a function to update the employee profile.

At this point, if you still don’t have an AngularJS module declared just declare one with a name of your choice, I’m going to use ‘angularjsServicesExample':

var app = angular.module('angularjsServicesExample',[]);

With our module created we can now start adding services to it:

app.service('productService', function($http, $q){
    this.isAvailable = function(productId){
        console.log('productService.isAvailable called!!');
    }
    this.getInfo = function(){
        console.log('productService.getInfo called!!');
    }
});
 
app.service('employeeService', function($http, $q){
    this.updateProfile = function(newInfo){
        console.log('employeeService.updateProfile called!!');
    }
});

Really simple, right? But how do we use these services? Using them is even easier, you just need to add them to your controller, then you can just call your functions:

app.controller('myController', function($scope, productService, employeeService){
    productService.isAvailable('1');
    productService.getInfo();
    employeeService.updateProfile('test');
});

That’s it!! If you run your project you’ll see the texts printed on the console.

Thanks for reading this tutorial, hope it was helpful for you, if you have any doubt just leave a comment.
Till the next one!!

AngularJS Tutorial: Consuming Java EE Web Services

It’s very common to see people asking how to integrate Java EE applications with some of the popular JavaScript frameworks, specially with AngularJS. In most cases developers already have an application (or a great portion of it) written in Java EE containing all the business logic, and since it’s not feasible to rewrite everything in JavaScript, they look for ways to integrate and add new technology to the project without losing any existing code.

That’s when Web Services comes in handy!! They allow your AngularJS application to send and receive data from the Java EE module in a very easy way. Of course there are more sophisticated ways to do this communication, but that is a subject for another post.

The first step is to expose the Web Service in your Java EE project, I’m assuming that you already have this project ready, but if you don’t, just create one by following the instructions in this link.

Now that you already have your web service, make sure it’s working before you continue, to do that, open your browser and call your service by typing it’s URL, it should follow this pattern:

1
2
3
{domain}:{port}/{projectName}/{webServicePath}
 
//example: http://localhost:8080/WebServiceEJB-war/test

If everything is right the browser will display the data returned by your web service, if it doesn’t you’re probably missing something, make sure you followed every instruction in the example I mentioned above.

Now we can start writing some AngularJS code, after setting up the project let’s create the app.js file like this:

1
2
3
4
5
6
7
var app = angular.module('angularWS',[]);
app.controller('myController', function($scope, $http){
	$http.get('http://localhost:8080/WebServiceEJB-war/test')
		.success(function(data){
			$scope.text = data;		
		});	
});

This is the simplest way to consume a web service with angular, the $http.get function will make the request to the Java EE application, all you need to do is to pass the web service URL, when it receives the data, it will execute the callback passed to the success() function, there you can do anything you want with the data, in my case I’m just assigning it to the $scope.text variable. When your Angular application make the request, it’ll probably get an Cross-Origin Request Blocked error, in this case just follow the steps in this link to fix it.

Tutorial: ng-table with infinite scroll

I’ve already showed in this blog how to create a basic datatable with ng-table, for those who didn’t see it yet, just click on the link. This tutorial will just be a complement to the previous one, the difference is that instead of using pagination I’m going to use infinite scroll, and don’t worry, I’ll also keep the sorting and filtering features.

So before we start let’s just put the links to every script we need, your index.html should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html ng-app="ngTableTutorial">
    <head>
        <title>ng-table with infinite scroll</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.js"></script>
        <script src="https://raw.githubusercontent.com/BinaryMuse/ngInfiniteScroll/1.0.0/build/ng-infinite-scroll.min.js"></script>
        <link rel="stylesheet" href="https://rawgit.com/esvit/ng-table/master/dist/ng-table.min.css">
        <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" media="screen">
 
        <script src="app/resources/js/app.js" type="text/javascript"></script>
        <link href="app/resources/css/style.css" rel="stylesheet" type="text/css"/>
    </head>
    <body style="padding: 50px">
        <div ng-controller="tableController">
        </div>
    </body>
</html>

As you can see I just put the links to: JQuery, Angular, bootstrap, ng-table and ngInfiniteScroll. There’s also the app.js and style.css, which I created to put my code on them.

Note that the body is still empty for now, let’s leave it like this and open our app.js, the first thing we need to do is to create our angular module and controller, just copy the following code to your app.js:

1
2
3
4
angular.module('ngTableTutorial', ['ngTable','infinite-scroll'])
        .controller('tableController', function ($scope, $filter, ngTableParams) {
        }
);

Don’t forget to declare the ngTable and infinite-scroll as dependencies, we’re going to use them later. This code is still very simple, I just created a module called ngTableTutorial, if you go back to the index.html code you’ll see that the ng-app=”ngTableTutorial” is already there in the html tag, and I also created a controller called tableController, again if go to the index.html there will be a div inside our body with the attribute ng-controller=”tableController”.

Now we need some data to be displayed to the table, I personally like mockaroo to generate random data, but feel free to generate it as you like, you’ll need about 1000 rows for this tutorial, after you generate it, just put it in a variable inside you controller, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$scope.users =
        [{
                "id": 1,
                "first_name": "Theresa",
                "last_name": "Morris",
                "email": "tmorris0@myspace.com",
                "country": "Indonesia",
                "ip_address": "143.220.154.199"
            }, {
                "id": 2,
                "first_name": "Steve",
                "last_name": "Gray",
                "email": "sgray1@nytimes.com",
                "country": "Norway",
                "ip_address": "163.199.165.94"
            }
           .
           .
           .
            {
                "id": 1000,
                "first_name": "Gloria",
                "last_name": "West",
                "email": "gwest2@go.com",
                "country": "China",
                "ip_address": "16.171.225.220"
            }
];

Now that we have the data we’re ready to create our table, copy the table bellow inside your div with the ng-controller attribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<table infinite-scroll="getMoreData()" ng-table="tableParams" show-filter="true" class="table table-striped">
    <tr ng-repeat="user in data">
        <td data-title="'Id'" sortable="'id'">
            {{user.id}}
        </td>
        <td data-title="'First Name'" sortable="'first_name'" filter="{ 'first_name': 'text' }">
            {{user.first_name}}
        </td>
        <td data-title="'Last Name'" sortable="'last_name'" filter="{ 'last_name': 'text' }">
            {{user.last_name}}
        </td>    
        <td data-title="'e-mail'" sortable="'email'">
            {{user.email}}
        </td>    
        <td data-title="'Country'" sortable="'country'">
            {{user.country}}
        </td>    
        <td data-title="'IP'" sortable="'ip_address'">
            {{user.ip_address}}
        </td>    
    </tr>
</table>

Each column is displaying one attribute of our JSON, I put the attribute sortable and filter in some of them to add the sorting and filtering features to the datatable (to show the filter you also have to put show-filter=”true” in your table). But what is important here is the attributes ng-table=”tableParams” and infinite-scroll=”getMoreData()” from the table, the first is binding the table to the tableParams variable in our controller (I’m still going to create this variable), and the second attribute receives the method that will be called when the user reaches the bottom of the page, that’s the method that will make our infinite scroll work.

Now the only thing left for us to do is to create our tableParams and implement the getMoreData() method, copy the following code bellow our JSON in your controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$scope.tableParams = new ngTableParams({
    page: 1,
    count: $scope.users.length
}, {
    counts: [],
    total: 1,
    getData: function ($defer, params) {
        $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
        $scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
        $scope.data = $scope.data.slice(0, 20);
        $defer.resolve($scope.data);
    }
});
 
$scope.getMoreData = function () {
    $scope.data = $scope.users.slice(0, $scope.data.length + 20);
}

In this code we are instantiating the ngTableParams, the fist object it receives as a parameter is just defining that the current page is 1 and setting the row count, but what really matters here is the function getData, it will be called on the table initialization and also every time we sort or filter it, the lines 8 and 9 contains the logic to sort and filter the data, note that in line 10 I’m getting only the first 20 rows of our data, I’m doing this because every time this method is called, or the user will be filtering the data or he’ll be sorting it, both actions require him to be on the top of the page, thus I don’t need to show more than 20 rows.

Ok, now we just need to load more rows when he reaches the bottom of the pages, take a look at line 16, it’s just adding 20 more rows to our data, note that I’m using 2 variables here: $scope.data and $scope.users. The last one contains our original data, we cannot modify it, otherwise we’ll lose the data, that’s why we need an auxiliary variable, just to manipulate the data.

That’s it, now if you run your project you should see the following result:

ngTable with Infinite scroll
ng-Table with infinite scroll

As you scroll down you’ll see that the scroll bar will get smaller and smaller.