Posts on this Category



How to use ES6 (Very Simple Example)

Compiling Javascript ES6 Code with Babel
Compiling Javascript ES6 Code with Babel

This will be a very simple tutorial on how to use, the new and far more sophisticated version of Javascript, the ES6 (or ES2015 if you prefer). Much people say ES6 is the future of Javascript, but as everybody knows, our browsers cannot run code in this format yet. Web developers are already writing Javascript in ES6 format and using transpilers to transform it into ES5 code so the browsers can read it. For those who doesn’t know, a transpiler is kind of a compiler that converts a code written in one programming language to another similar programming language, in our case from ES6 to ES5.

The reason why I decided to make it simple is because I’ve already seen lots of authors writing more complex and long tutorials involving Grunt, Browserify, JSX, and so on. You would probably spend a reasonable amount of time going through these tutorials. As opposed to them, my goal here is to get you writing ES6 code as quickly as possible, without consuming much of your time.

So let’s get started, the first thing we need is a transpiler, for this tutorial I’m going to be using Babel, to install it just run the following command:

1
npm install babel-cli -g

Now, since Babel doesn’t come with any transformations enabled, we need to explicitly tell what kind of transformation to perform, to do that we also have to install ES2015 preset:

1
npm install babel-preset-es2015 -g

Perfect! Now we’re going to need to write some ES6 code to test if Babel is working, copy the following code into a js file:

test.js

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyFirstES6Class {
  constructor(message) {
    this._message = message;
  }
 
  get message() {
    return this.message;
  }
 
}
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Ok, now via terminal just navigate to your folder and run the following command to generate the compiled js:

1
babel --presets es2015 test.js --out-file compiled.js

That’s it!! If you did it right you should now have the compiled.js file containing the transformed code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { 
throw new TypeError("Cannot call a class as a function"); } }
 
var MyFirstES6Class = (function () {
  function MyFirstES6Class(message) {
    _classCallCheck(this, MyFirstES6Class);
 
    this._message = message;
  }
 
  _createClass(MyFirstES6Class, [{
    key: 'message',
    get: function get() {
      return this.message;
    }
  }]);
 
  return MyFirstES6Class;
})();
 
var myClass = new MyFirstES6Class('Hello World!!');
console.log(myClass.message);

Node.js Tutorial: Reading and Writing files

Reading and writing files is a very trivial task, no matter what programming language you use you probably have already came across a situation where you had to do it, and it’s not different for node.js developers, luckily node.js makes this task very easy for us, with the file system(fs) module we can easily read files with very few lines of code as the following example:

1
2
3
4
5
6
7
var fs = require('fs');
 
fs.readFile('C:\\file.txt', 'utf8', displayData);  
 
function displayData(err,data){
  console.log(data);
}

In the example above I’ve just used the fs.readFile function to read a file located on my ‘C:\’, besides the file path I also provided the encoding and a callback which will be called once the file content is ready.

Now that we already know how to read files, let’s learn how to write files, it’s as easy as reading them, take a look at the following code:

1
2
3
4
5
6
7
8
9
10
11
var fs = require('fs');
 
fs.writeFile('C:\\file.txt', 'My Content', showMessage);  
 
function showMessage(err){
  if(err) {
    console.log(err);  
  }else{
    console.log('Your data has been successfully written!');    
  }
}

It’s basically the same thing we saw on the first example, except that instead of using the readFile function I used the writeFile, also the second argument is the content I want to write on the file, and once again we have a callback that will execute after the content is written.

If you run this code more than once you should note that before writing your content it erases everything that is already on the file, to prevent this from happening you should use the function appendFile instead of writeFile.

AngularJS Tutorial: ui-router example

Since ui-router is one of the most useful features that angular can provide I decided to write this tutorial just to show how to use it, I’m going to create a very simple application that illustrates how to create templates using ui-router states.

After donwloading angular.min.js and angular-ui-router.min.js let’s create our index.html and include both:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html ng-app="uiRouterExample">
    <head>
        <title>ui-router example</title>
        <script src="js/angular.min.js" type="text/javascript"></script>
        <script src="js/angular-ui-router.min.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </head>
    <body>
        <div ui-view></div>
    </body>
</html>

This file will be our template, it will be the same no matter the state, note that inside the body I have a div with the ui-view attribute, that’s where our states will be included.

With the index.html ready let’s create the app.js:

1
2
3
4
5
6
7
8
9
10
11
var app = angular.module('uiRouterExample', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider.state("state1", {
        url: "/state1",
        templateUrl: "states/state1.html"
    }).state("state2", {
        url: "/state2",
        templateUrl: "states/state2.html"
    });
    $urlRouterProvider.otherwise("/state1");
});

I tried to make this code as simple as possible, I’ve just created 2 states named ‘state1′ and ‘state2′, each one of them receives an object containing the attributes ‘url’ and ‘templateUrl’, the first one is the path we’re going to type on our browser to call the states, and the second is the html file that will be displayed when the state is called.

Lastly I’m making state1 the default state by passing its path to $urlRouterProvider.otherwise function, this way when the application is first loaded the state1 will be called by default.

Now let’s take a look at out state1.html and state2.html:

1
2
3
4
5
6
7
8
9
<!--state1.html-->
This is the State1
<br />
<a ui-sref="state2">Go to state2</a>
 
<!--state2.html-->
This is the State2
<br />
<a ui-sref="state1">Go to state1</a>

If you run your project, since state1 is your default state, you’re going to see the state1.html rendered on your screen, and if you click on the link you’re going to be redirected to state2.

Tutorial: Creating Node.js modules

Node.js Modules

In this short tutorial I’m going to explain how you can create your own modules in Node.js, as everyone knows we cannot keep our entire code in only one js file, as your application grows it’ll be almost impossible for you to maintain your code, for this reason it’s essential that we separate our code in modules, this way it’ll hopefully always be organized and easy to maintain.

Node.js makes it very easy for us to create custom modules, let’s suppose we need to put 2 functions in a separated module, we just need to create a new js file like this:

newModule.js

1
2
3
4
5
6
7
exports.function1 = function(){
	console.log('Function 1');
}
 
exports.function2 = function(){
	console.log('Function 2');
}

As you can see it’s a very straightforward code, all I did was to create 2 functions and add them to module.exports, unless you don’t want your functions to be visible to other modules it’s very important that you add them to exports.

Now you can require this new module in another module as follows:

app.js

1
2
3
4
var newModule = require('./newModule');
 
newModule.function1();
newModule.function2();

When requiring a module you have to pass its full path to the require function, in this example I’m assuming that the 2 js files are in the same folder. After requiring your module you’re done! Now this app.js file has access to all the functions you’ve exported from your new module.

Tutorial: Creating Reusable Code with AngularJS Directives

AngularJS Directives

I know this may not be new for most of you, but when it comes to directives a lot of people still get really confused, so let’s start by looking at its definition, according to AngularJS documentacion:

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

In other words, they allow us to create our own DOM elements that can be reused all over the place, imagine that you have a block of HTML code that you know you’re going to use in several places, instead of just coping and pasting it everywhere, you can create a directive and use it wherever you need, it’ll be a lot easier for you to maintain your code, if something changes in this HTML block you just have to modify your directive, and the changes will reflect across your application.

It will be easier to understand with an example, let’s create a project containing the following files:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html ng-app="directivesTutorial">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="app/resources/js/app.js" type="text/javascript"></script>
    </head>
    <body >
        <div ng-controller="directivesTutorialController">
            <div ng-repeat="company in companies">
                <p>Company: {{company.name}} - City: {{company.city}}</p>
            </div>
        </div>
    </body>
</html>

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
var app = angular.module('directivesTutorial', []);
app.controller('directivesTutorialController', function ($scope, $http) {
    $scope.companies = [{"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"}];
});

Nothing different for now, we’ve seen this a million times, it’s just a ng-repeat iterating over a JSON (in this case a list of campanies), note that inside the ng-repeat div we have a small block of code that displays the company information, of course this block would be more complex in a real scenario, but let’s suppose we need to reuse it to display the same data in other parts of the application, to achieve that we’re going create a directive called ‘company’ which will be responsible for displaying the company data.

Copy the code bellow to another js file, let’s call it ‘campany.js':

1
2
3
4
5
6
7
8
var companyDirective = angular.module('directives.company', []);
companyDirective.directive('company', function () {
    return{
        retrict: 'E',
        scope: {object: '='},
        templateUrl: "templates/company.html"
    };
});

That’s our directive’s code, you can see that it returns an object containing 3 attributes, the first one is the “retrict: ‘E'”, it means that our directive will be restricted to elements, in other words it will be a DOM element.

The second one is the “object: ‘='”, by declaring this ‘object’ variable we’re saying that our directive will have an attribute called ‘object’, we’re going to use this attribute to pass the company we want the data to be displayed.
And lastly we have our templateUrl that receives the path to an html file containing the directive’s html code.

Our company.html should look like this:

1
<p>Company: {{object.name}} - City: {{object.city}}</p>

Note that it’s the same code as before, the only difference is that instead of using the variable ‘company’ we’re using ‘object’ which is the name of the attribute we defined before.

We’re almost done, now you just have to add to your index.html a reference to company.js:

1
<script src="{YOUR_PATH}/company.js" type="text/javascript"></script>

and also put the directive as a dependency in your app.js:

1
var app = angular.module('directivesTutorial', ['directives.company']);

That’s it! Now our ng-repeat can be rewritten using our new directive:

1
2
3
<div ng-repeat="company in companies">
    <company object="company"></company>
</div>

You now have the ‘company’ element that can be reused anywhere in your application.

Related Posts:
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table
Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll

Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll

Over the past few years the infinite scroll has became very popular across the web, developers are increasingly choosing to use infinite scroll over the conventional paginator. The advantage is that it doesn’t require the user to manually go to the next page when he reaches the end of the page, it automatically loads and display more data without the user intervention.

In this tutorial I’m going to show how to implement infinite scroll using ngInfiniteScroll for AngularJS.

First create the js and html file:

app.js

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
29
30
31
angular.module('infiniteScrollTutorial', ['infinite-scroll'])
        .controller('infiniteScrollController', function ($scope, $http) {
            $scope.users =
                    [{
                            "id": 1,
                            "first_name": "Kimberly",
                            "last_name": "Grant",
                            "email": "kgrant0@ebay.co.uk",
                            "country": "Bolivia",
                            "ip_address": "93.77.148.179"
                        }, {
                            "id": 2,
                            "first_name": "Elizabeth",
                            "last_name": "Lewis",
                            "email": "elewis1@so-net.ne.jp",
                            "country": "Indonesia",
                            "ip_address": "39.187.159.25"
                        },
                        .
                        .
                        .
 
                        {
                            "id": 100,
                            "first_name": "Shawn",
                            "last_name": "Ellis",
                            "email": "sellis2r@diigo.com",
                            "country": "Portugal",
                            "ip_address": "121.250.152.235"
                        }];
});

index.html

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
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html ng-app="infiniteScrollTutorial">
    <head>
        <title>TODO supply a title</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="https://raw.githubusercontent.com/BinaryMuse/ngInfiniteScroll/1.0.0/build/ng-infinite-scroll.min.js"></script>
        <script src="app/resources/js/app.js" type="text/javascript"></script>
        <style>
            .userContainer{
                width:500px;
                height:110px;
                background: #f9f9f9;
                padding: 5px;
                font-family: verdana;
                margin-bottom: 7px;
                box-shadow: 0px 0px 2px 1px;
            }
            .userContainer p{
                font-size: 12px;
            }
        </style>
    </head>
    <body>
        <div ng-controller="infiniteScrollController">
            <div >
                <div ng-repeat="user in users" class="userContainer">
                    <h4>{{user.first_name}} {{user.last_name}}</h4>
                    <p>
                        <b>Email:</b> {{user.email}}  -   
                        <b>Country:</b> {{user.country}}  -  
                        <b>IP:</b> {{user.ip_address}} 
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>

Nothing special for now, except that I’ve already added the dependency ‘infinite-scroll’ in the angular module declaration, besides that we just have a regular ng-repeat iterating over a JSON (you should make this JSON as big as you can, it will be easier for you to see the results, you can use mockaroo to gerenate some JSON data).

Now let’s change the code a little bit to make the infinite scroll work, we’re going to add the attribute ‘infinite-scroll’ in the div above the one with the ng-repeat, after the modification it should look like this:

1
2
3
4
5
6
7
8
9
10
<div infinite-scroll="getMoreData()">
    <div ng-repeat="user in data" class="userContainer">
        <h4>{{user.first_name}} {{user.last_name}}</h4>
        <p>
            <b>Email:</b> {{user.email}}  -   
            <b>Country:</b> {{user.country}}  -  
            <b>IP:</b> {{user.ip_address}} 
        </p>
    </div>
</div>

Note that the new attribute is referencing the function getMoreData(), which will be called every time the bottom of the element approaches the bottom of the browser window, in this function we’ll have to write the code to get more data, also note the I’m not using the variable ‘users’ anymore in the ng-repeat, instead I’m using the auxiliary variable ‘data’.

Let’s take a look at the getMoreData() code, add this bellow the JSON in your app.js:

1
2
3
4
$scope.data = $scope.users.slice(0, 5);
$scope.getMoreData = function () {
    $scope.data = $scope.users.slice(0, $scope.data.length + 5);
}

I’m initializing the $scope.data with the 5 first elements of the $scope.users, and the function getMoreData is just adding five more elements every time it gets called.

Now if you run you application you’ll see the following result:

AngularJS infinite Scroll
AngularJS infinite Scroll

That’s it! At first it’ll have only 5 elements loaded and as you scroll down it will start loading more.

Related Posts:
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table
Tutorial: Creating Reusable Code with AngularJS Directives

Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table

In this tutorial I’m going to show you how to create a simple DataTable with some basic features, which are sorting, filtering and pagination. To accomplish this I’m going to use AngularJS with the module ng-Table.

First we need to create our project, after doing it, no matter your folder structure, you should have a html file to host your table (I’m going to use index.html) and also a js file to put your angular code (app.js).

Initially they should look like this:

Index.html

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

app.js

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

I’ve already referenced all the js and css files we’re going to use, and as you can see, I have also defined the angular module and controller. This is our initial project structure, if you run it, since we didn’t added anything yet, you’ll just see a blank page on your browser.

Now let’s get started with our table, the first thing we need is some data display on it, since we’re not using a database for this tutorial, a static JSON will do the job (You can use the website mockaroo to generate some data to test your app). After you get the data you can store it in a variable on your controller, your code should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
angular.module('ngTableTutorial', ['ngTable'])
        .controller('tableController', function ($scope, $filter, ngTableParams) {
 
            $scope.users = [{"id":1,"first_name":"Philip","last_name":"Kim","email":"pkim0@mediafire.com","country":"Indonesia","ip_address":"29.107.35.8"},
                        {"id":2,"first_name":"Judith","last_name":"Austin","email":"jaustin1@mapquest.com","country":"China","ip_address":"173.65.94.30"},
                        {"id":3,"first_name":"Julie","last_name":"Wells","email":"jwells2@illinois.edu","country":"Finland","ip_address":"9.100.80.145"},
                        {"id":4,"first_name":"Gloria","last_name":"Greene","email":"ggreene3@blogs.com","country":"Indonesia","ip_address":"69.115.85.157"},
                        .
                        .
                        .
                        {"id":50,"first_name":"Andrea","last_name":"Greene","email":"agreene4@fda.gov","country":"Russia","ip_address":"128.72.13.52"}];
 
            });
        });

With the data available we can now start creating our table on the index.html, the first feature we’re going to implement will be the pagination, although it’s getting old, I’m going to use it anyway for this tutorial, but I strongly recommend you to create a table with infinite scroll, I’ll show you how to do that in another tutorial.

To create the table just put the following code inside your div tag:

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

This is the table structure with all the available columns of our JSON, if your data has different columns you just have to change their names in the td tag. An important thing to note is that I didn’t use our users variable in the ng-repeat, later I will explain why.

Also note that I’ve already defined the ng-table attribute in the table tag, now we have to declare it on the app.js, copy this code and put it below the $scope.users declaration:

1
2
3
4
5
6
7
8
9
10
$scope.usersTable = new ngTableParams({
                page: 1,
                count: 10
            }, {
                total: $scope.users.length, 
                getData: function ($defer, params) {
                    $scope.data = $scope.users.slice((params.page() - 1) * params.count(), params.page() * params.count());
                    $defer.resolve($scope.data);
                }
            });

All I’m doing is defining the page size and also the initial page, this is done by the ‘count’ and ‘page’ attributes respectively. But the most important thing here is the getData function, it will be called every time you refresh our table, in other words, every time you filter, paginate or sort our data. Since our only feature is pagination for now, the getData function will only be responsible to get from the $scope.users the data displayed on our current page, I’ve used the splice function for that and stored the results in my auxiliary variable $scope.data (I couldn’t use the $scope.users because it would override my initial data).

If you run your project this will be the result:

ng-TableWithPagination
ng-Table with pagination

Now let’s add the sort functionality to the table, in your index.html just add the attribute sortable to the columns. Here is one example:

1
2
3
<td data-title="'Id'" sortable="'id'">
    {{user.id}}
</td>

You also need to change a little bit the getData function:

1
2
3
4
5
getData: function ($defer, params) {
   $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
   $scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
   $defer.resolve($scope.data);
}

I just added the first line which is responsible for sorting the data before slicing and returning it.

The last feature we’re going to add is the filter, as we did for the sorting functionality we’re just going to add one more attribute to the columns, the ‘filter’:

1
2
3
<td data-title="'First Name'" sortable="'first_name'" filter="{ 'first_name': 'text' }">
  {{user.first_name}}
</td>

For enable filtering we also have to put the attribute show-filter on the table:

1
<table ng-table="usersTable" show-filter=”true” class="table table-striped">

And lastly, add one more line to the getData function, which will be responsible for filtering our data:

1
2
3
4
5
6
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((params.page() - 1) * params.count(), params.page() * params.count());
   $defer.resolve($scope.data);
}

if you run your project you’ll see the final result:

ng-Table with sort, filter and pagination features
ng-Table with sort, filter and pagination features

That’s it, now we have our datatable with sorting, filtering and pagination.
Hope this tutorial was helpful for you.
Till next time!

Related Posts:
Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll
Tutorial: Creating Reusable Code with AngularJS Directives