Sandeep is a web developer and writer with a passion for Java, JavaScript and HTML5. He has 4+ years of experience programming for the web. He loves experimenting with new technologies as they emerge and his current love interest is AngularJS. Sandeep always looks forward to working with new and exciting opportunities. While not programming, he can be found playing games and listening to music. You can also find him blogging about various web technologies on his own website HTMLxprs.

Sandeep's articles

  1. 10 Tips to Make Your Node.js Web App Faster

    Node.js is already blazing fast thanks to its event driven and asynchronous nature. But, in the modern web just being fast is not enough. If you are planning to develop your next web app using Node.js you must take every possible step to make sure your app is faster than usual. This article presents 10 tips that are known to speed up your Node based web app tremendously. So, let’s see each of them one by one.

    1. Run in Parallel

    While building web apps, sometimes you will need to make multiple internal API calls to fetch various data. For instance, think about a user dashboard. While rendering the dashboard you may execute the following hypothetical calls:

    • The user profile – getUserProfile().
    • The recent activity – getRecentActivity().
    • Subscriptions – getSubscriptions().
    • Notifications – getNotifications().

    In order to retrieve these details you might create a separate middleware for each function and attach to the dashboard route. But the problem with this approach is that one function has to wait for the previous one to complete. The alternative option is to execute these calls in parallel.

    As we all know Node.js is very efficient in running multiple functions in parallel due to its asynchronous nature. We should take advantage of this. As the functions I mentioned above don’t depend on each other we can run them in parallel. This will cut down the number of middlewares and improve the speed greatly.

    To parallelize things we can use async.js, a Node module that helps tame asynchronous JavaScript. Here is a snippet that shows how different functions may run in parallel using async.js:

    [js]
    function runInParallel() {
    async.parallel([
    getUserProfile,
    getRecentActivity,
    getSubscriptions,
    getNotifications
    ], function(err, results) {
    //This callback runs when all the functions complete
    });
    }
    [/js]

    If you want to learn more about async.js be sure to check out the project’s GitHub page.

    2. Go Asynchronous

    By design Node.js is single threaded. Because of this fact, synchronous code can potentially lock up the entire application. For example, most of the file system APIs have their synchronous counterparts. The following snippet shows how a file read operation can be done both synchronously and asynchronously:

    [js]
    // Asynchronous
    fs.readFile(‘file.txt’, function(err, buffer) {
    var content = buffer.toString();
    });

    // Synchronous
    var content = fs.readFileSync(‘file.txt’).toString();
    [/js]

  2. Creating RESTful APIs with Express 4

    With the release of Express 4 it has gotten even easier to create RESTful APIs. If you are creating a Single Page App you will definitely need a RESTful web service which supports CRUD operations. My last tutorial focussed on creating a Single Page CRUD app with Angular’s $resource. This tutorial explains how to design the backend API for such a CRUD app using Express 4.

    Just note that a lot has been changed since Express 3. This tutorial doesn’t explain how to upgrade your app from Express 3 to Express 4. Rather it will cover how to create the API with Express 4 directly. So, let’s get started.

    Creating the API for the Movie App

    Our app will be a simple movie database which supports basic CRUD operations. We will use Express 4 as the web framework and MongooseJS as the object modeling tool. To store the movie entries we will use MongoDB.

    Before going further let’s take a look at what the API will look like:

    API Overview

    Directory Structure

    We will use the following directory structure in our app:

    App Directory Structure

    Here are some points about the above directory structure:

    1. The bin/www.js is used to bootstrap our app.
    2. The models directory stores our mongoose models. For this app we will have just one file called movie.js.
    3. The routes directory will store all the Express routes.
    4. The app.js holds the configurations for our Express app.

    Finally, node_modules and package.json are the usual components of a Node.js app.

    Obtaining Necessary Dependencies

    To create the API we will use the following modules:

    1. Express
    2. Body parser
    3. Mongoose

    Notebody-parser is not a part of the Express core anymore. You need to download the module separately. So, we have listed it in the package.json.

    To obtain these packages we will list them as dependencies in our package.json. Here is our package.json file:

  3. Creating a CRUD App in Minutes with Angular’s $resource

    Most Single Page Applications involve CRUD operations. If you are building CRUD operations using AngularJS, then you can leverage the power of the $resource service. Built on the top of the $http service, Angular’s $resource is a factory that lets you interact with RESTful backends easily. So, let’s explore $resource and use it to implement CRUD operations in Angular.

    Prerequisites

    The $resource service doesn’t come bundled with the main Angular script. You need to download a separate file called angular-resource.js and include it in your HTML page. The script can be downloaded from http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js.

    Also, your main app module should declare a dependency on the ngResource module in order to use $resource. The following example demonstrates how to do it:

    [js]
    angular.module(‘mainApp’,['ngResource']); //mainApp is our main module
    [/js]

    Getting Started

    $resource expects a classic RESTful backend. This means you should have REST endpoints in the following format:

    REST Endpoints

    You can create the endpoints using the server side language of your choice. However, I have used Node + Express + MongoDB to design the RESTful API for the demo app. Once you have the URLs ready you can take help of $resource for interacting with these URLs. So, let’s see how exactly $resource works.

    How Does $resource Work?

    To use $resource inside your controller/service you need to declare a dependency on $resource. The next step is calling the $resource() function with your REST endpoint, as shown in the following example. This function call returns a $resource class representation which can be used to interact with the REST backend.

    [js]
    angular.module(‘myApp.services’).factory(‘Entry’, function($resource) {
    return $resource(‘/api/entries/:id’); // Note the full endpoint address
    });
    [/js]

    The result of the function call is a resource class object which has the following five methods by default:

    1. get()
    2. query()
    3. save()
    4. remove()
    5. delete()

    Now, let’s see how we can use the get(), query() and save() methods in a controller:

    [js]
    angular.module(‘myApp.controllers’,[]);

    angular.module(‘myApp.controllers’).controller(‘ResourceController’,function($scope, Entry) {
    var entry = Entry.get({ id: $scope.id }, function() {
    console.log(entry);
    }); // get() returns a single entry

    var entries = Entry.query(function() {
    console.log(entries);
    }); //query() returns all the entries

    $scope.entry = new Entry(); //You can instantiate resource class

    $scope.entry.data = ‘some data’;

    Entry.save($scope.entry, function() {
    //data saved. do something here.
    }); //saves an entry. Assuming $scope.entry is the Entry object
    });
    [/js]

    The get() function in the above snippet issues a GET request to /api/entries/:id. The parameter :id in the URL is replaced with $scope.id. You should also note that the function get() returns an empty object which is populated automatically when the actual data comes from server. The second argument to get() is a callback which is executed when the data arrives from server. This is a useful trick because you can set the empty object returned by get() to the $scope and refer to it in the view. When the actual data arrives and the object is populated, the data binding kicks in and your view is also updated.

    The function query() issues a GET request to /api/entries (notice there is no :id) and returns an empty array. This array is populated when the data arrives from server. Again you can set this array as a $scope model and refer to it in the view using ng-repeat. You can also pass a callback to query() which is called once the data comes from server.

    The save() function issues a POST request to /api/entries with the first argument as the post body. The second argument is a callback which is called when the data is saved. You might recall that the return value of the $resource() function is a resource class. So, in our case we can call new Entry() to instantiate an actual object out of this class, set various properties on it and finally save the object to backend.

    Ideally, you will only use get() and query() on the resource class (Entry in our case). All the non GET methods like save() and delete() are also available in the instance obtained by calling new Entry() (call this a $resource instance). But the difference is that these methods are prefixed with a $. So, the methods available in the $resource instance (as opposed to $resource class) are:

    1. $save()
    2. $delete()
    3. $remove()

    For instance, the method $save() is used as following:

    [js]
    $scope.entry = new Entry(); //this object now has a $save() method
    $scope.entry.$save(function() {
    //data saved. $scope.entry is sent as the post body.
    });
    [/js]

    We have explored the create, read and delete parts of CRUD. The only thing left is update. To support an update operation we need to modify our custom factory Entity as shown below.

    [js]
    angular.module(‘myApp.services’).factory(‘Entry’, function($resource) {
    return $resource(‘/api/entries/:id’, { id: ‘@_id’ }, {
    update: {
    method: ‘PUT’ // this method issues a PUT request
    }
    });
    });
    [/js]
  4. Understanding Angular’s $apply() and $digest()

    $apply() and $digest() are two core, and sometimes confusing, aspects of AngularJS. To understand how AngularJS works one needs to fully understand how $apply() and $digest() work. This article aims to explain what $apply() and $digest() really are, and how they can be useful in your day-to-day AngularJS programming.

    $apply and $digest Explored

    AngularJS offers an incredibly awesome feature known as two way data binding which greatly simplifies our lives. Data binding means that when you change something in the view, the scope model automagically updates. Similarly, whenever the scope model changes, the view updates itself with the new value. How does does AngularJS do that? When you write an expression ({{aModel}}), behind the scenes Angular sets up a watcher on the scope model, which in turn updates the view whenever the model changes. This watcher is just like any watcher you set up in AngularJS:

    [js]
    $scope.$watch(‘aModel’, function(newValue, oldValue) {
    //update the DOM with newValue
    });
    [/js]

    The second argument passed to $watch() is known as a listener function, and is called whenever the value of aModel changes. It is easy for us to grasp that when the value of aModel changes this listener is called, updating the expression in HTML. But, there is still one big question! How does Angular figure out when to call this listener function? In other words, how does AngularJS know when aModel changes so it can call the corresponding listener? Does it run a function periodically to check whether the value of the scope model has changed? Well, this is where the $digest cycle steps in.

    It’s the $digest cycle where the watchers are fired. When a watcher is fired, AngularJS evaluates the scope model, and if it has changed then the corresponding listener function is called. So, our next question is when and how this $digest cycle starts.

    The $digest cycle starts as a result of a call to $scope.$digest(). Assume that you change a scope model in a handler function through the ng-click directive. In that case AngularJS automatically triggers a $digest cycle by calling $digest(). When the $digest cycle starts, it fires each of the watchers. These watchers check if the current value of the scope model is different from last calculated value. If yes, then the corresponding listener function executes. As a result if you have any expressions in the view they will be updated. In addition to ng-click, there are several other built-in directives/services that let you change models (e.g. ng-model, $timeout, etc) and automatically trigger a $digest cycle.

    So far, so good! But, there is a small gotcha. In the above cases, Angular doesn’t directly call $digest(). Instead, it calls $scope.$apply(), which in turn calls $rootScope.$digest(). As a result of this, a digest cycle starts at the $rootScope, and subsequently visits all the child scopes calling the watchers along the way.

    Now, let’s assume you attach an ng-click directive to a button and pass a function name to it. When the button is clicked, AngularJS wraps the function call within $scope.$apply(). So, your function executes as usual, change models (if any), and a $digest cycle starts to ensure your changes are reflected in the view.

    Note: $scope.$apply() automatically calls $rootScope.$digest(). The $apply() function comes in two flavors. The first one takes a function as an argument, evaluates it, and triggers a $digest cycle. The second version does not take any arguments and just starts a $digest cycle when called. We will see why the former one is the preferred approach shortly.

  5. Creating Three Way Data Binding with FireBase and AngularJS

    As you may know, FireBase acts as a realtime backend for your apps. Well, we all know how awesome this is. But you know what’s more awesome? It’s AngularJS+FireBase. FireBase has an officially released binding called AngularFire that brings all the fun and joy of FireBase to AngularJS. As AngularJS developers we love data binding so much that we even dream about it! With AngularFire we can create some seriously awesome stuff by taking advantage of a three way data binding as opposed to the traditional two way data binding in AngularJS. This tutorial will give you an overview of three way binding while creating a simple realtime app using AngularFire. This article assumes that the reader is already aware of FireBase and has done some prior development in AngularJS.

    What’s Three Way Data Binding

    In AngularJS our scope model and view stay in sync thanks to the two way data binding. But if you introduce AngularFire, and thereby use FireBase as a backend, you empower yourself with a three way binding feature. You can basically bind your model data to a FireBase location so that whenever your models change, those changes are automatically pushed to FireBase. Similarly, whenever the data at the particular FireBase location changes, your local scope model is also updated. And, since our view and scope model are already in sync, this creates a three way data binding. The obvious benefit is that it lets you create cool realtime apps where the data changes frequently and those modifications are broadcast to all the connected users. All this happens without any significant effort. If you are building a chat application, a multiplayer game app, or a broadcast system you can leverage this feature.

    Getting Started

    To demonstrate the concept of three way binding, let’s create a sample application. Our application will be a realtime broadcast system where users can broadcast what they are typing in realtime. For each user there will be two options:

    • Start a broadcast
    • View a broadcast

    To start a broadcast the user needs to provide a name for the broadcast. Once the users type a name and click start, they can begin the broadcast. To view a broadcast, they need to choose a broadcast from a dropdown menu.

    Basic Architecture

    To start we need to find out how to store our broadcast data. First, login to FireBase and create a new FireBase storage. I created a FireBase called angularfiredemo, and hence we will be using the URL https://angularfiredemo.firebaseio.com to store data. Note that each FireBase location is represented by a URL, and we can have multiple broadcasts to handle the many users that will be using our system. Let’s store all our broadcasts under the location https://angularfiredemo.firebaseio.com/broadcasts. Each broadcast has two parts: the name and the content, represented by key/value pairs. A sample broadcast data is stored as shown in the following image.

    Sample Broadcast

    To view a broadcast, users will need to choose a particular broadcast name represented by the key in our FireBase. The next step for us is to build an AngularJS app around these key points.

    Those of you who are interested in the end product can checkout a demo at Plunker. To have a realtime experience, open two instances of your browser side by side. In the first instance, give your broadcast a name, start it, and then begin writing. In the second instance, choose the broadcast you just started from the dropdown menu. Now you can see the broadcast in realtime.

    Building the App

    To get started we need the following scripts:

    • AngularJS: The main AngularJS script.
    • FireBase: The script for enabling FireBase support.
    • AngularFire: FireBase binding for AngularJS.
    • Angular Route: For routing support in AngularJS.
    • Angular Sanitize: To sanitize incoming data from FireBase.

    To quickly design a layout we will use Bootstrap CSS.

    Step 1

    The first step is creating our main app module which is done like this:

    [js]
    angular.module(‘firebaseDemo’, ['firebase', 'ngSanitize', 'ngRoute']);
    angular.module(‘firebaseDemo’).constant(‘FIREBASE_URL’,’https://angularfiredemo.firebaseio.com/broadcasts’);
    [/js]

    Our main module depends on three other modules: firebase,ngSanitize, and ngRoute. All of the AngularFire functionality is encapsulated in its own module, firebase. ngSanitize and ngRoute are used for sanitizing the data and routing support respectively. We have also defined a constant, FIREBASE_URL, which reprsents the location that stores all the broadcasts.

    Step 2

    Now, let’s create a factory that retrieves the broadcasts from FireBase.

    [js]
    angular.module(‘firebaseDemo’).factory(‘broadcastFactory’, function($firebase,FIREBASE_URL) {
    return {
    getBroadcast: function(key) {
    return $firebase(new Firebase(FIREBASE_URL + ‘/’ + key));
    },
    getAllBroadcasts: function() {
    return $firebase(new Firebase(FIREBASE_URL));
    }
    };
    });
    [/js]

    Our factory broadcastFactory declares a dependency on FIREBASE_URL, which represents the location of our broadcasts. Our factory also depends on an AngularFire service called $firebase. It accepts a FireBase object and returns a special object which is kept in sync with the remote FireBase location. It has functions like $add(), $set(), $child(), etc. to work with data. Whenever an update is made to this local object, the change is pushed to the remote FireBase location.

    The factory has two functions:

    • getBroadcast(key): This returns a single object that represents a broadcast. This object has a property called $value which represents the content for the broadcast. We use this object to create a three way binding so that whatever the user types is constantly in sync with the remote FireBase location.
    • getBroadcasts(): This function returns an object that has all the broadcasts as its properties. We present this data to the users so that they can choose a broadcast to view.
  6. Understanding Knockout

    KnockoutJS is an elegant JavaScript library based on Model-View-ViewModel pattern that helps us create rich user interfaces effortlessly. If you are developing an application with sections that update dynamically whenever the underlying data model changes, then Knockout can really help you. The two way data binding and templating features in Knockout make the process of implementing dynamic views a breeze. This tutorial will get you started with Knockout, and show you how to use it in your own projects.

  7. Creating a Typeahead Widget with AngularJS

    If you are starting an AngularJS project you might want to have all the components written in Angular. Although it’s certainly possible to reuse the existing jQuery plugins, throwing a bunch of jQuery inside a directive is not always the correct way to do things. My advice would be to first check if the same thing can be implemented with pure Angular in a simpler/better way. This keeps your application code clean and maintainable. This tutorial, targeted towards beginners, walks the readers through the creation of a simple TypeAhead widget with AngularJS.

    Overview

    In this tutorial we are going to build a simple TypeAhead widget which creates suggestions as soon as someone begins typing into a text box. We will architect the app in such a way that the final product will be very configurable and can be plugged into an existing system easily. The basic steps involved in the creation process are:

    • Create a factory that interacts with a RESTful API, and returns JSON that will be used for auto complete suggestions.
    • Create a directive that will use the JSON data and encapsulate the typeahead input field.
    • Keep the directive configurable so that end users can configure the following options.

    Configuration Options

    1. The exact JSON object properties to show as part of the suggestions.
    2. The model in the controller’s scope that will hold the selected item.
    3. A function in the controller’s scope that executes when an item is selected.
    4. A placeholder text (prompt) for the typeahead input field.
  8. Creating a Slide Show Plugin With AngularJS

    Gone are the days when you used to write hundreds of lines of jQuery to create a custom image slider! It’s time to go Angular and achieve the same goal with smaller, simpler code. This tutorial will show how to create a slide show plugin with AngularJS. We will use Angular directives and animations to […]

  9. A Practical Guide to AngularJS Directives

    This entry is part 1 of 2 in the series A Practical Guide to AngularJS Directives

    This entry is part 1 of 2 in the series A Practical Guide to AngularJS DirectivesDirectives are the most important components of any AngularJS application. Although AngularJS ships with wide range of directives, you will often need to create application specific directives. This tutorial will give an overview of custom directives and explain how to […]