Ravi Kiran is a developer working on Microsoft Technologies at Hyderabad. These days, he is spending his time on JavaScript and particularly on Angular JS. He is an active blogger and a DZone MVB.

Ravi's articles

  1. JavaScript Animations in AngularJS Applications

    AngularJS is a feature-rich framework for creating single-page web applications, bringing all capabilities that one needs for building rich and interactive apps. One of the key features that Angular brings is the support of animations.

    We can animate a portion of the application to indicate a change occurring. In my last article I covered the support of CSS animations in Angular applications. In this article, we will see how to leverage JavaScript to animate the AngularJS apps.

    In Angular, the only difference between CSS and JavaScript animations is their definition. There is no difference in the way the defined animations are used. To start with, we need to load the ngAnimate module to the root module of our application.

    [code language="javascript"]
    angular.module('coursesApp', ['ngAnimate']);
    [/code]

    The animation events to be handled in the JavaScript animation also remain the same. Following is a list of directives supporting animations and their events for different actions:

    Directives Events
    ng-view
    ng-include
    ng-switch
    ng-if
    enter
    leave
    ng-repeat enter
    leave
    move
    ng-show
    ng-hide
    ng-class
    add
    remove

    The above listing is the same as the one in the previous article, but doesn’t mention the corresponding CSS classes, as we don’t need them to define JavaScript animations. These events are generated only if the application module loads the ngAnimate module. Now let us see how to animate some of the directives.

  2. Adding CSS Animations to AngularJS Applications

    AngularJS is meant for building rich data bound applications on the web. Adding animations to these applications feels just like having your favorite pizza with toppings. Animations not only add beauty to the UI, but they also make it more user friendly. A small animation in an app may elevate its richness to a level which is otherwise very difficult to achieve.

    With the power of the web these days, there are several ways to create animations. Until fairly recently, the animations were possible only with JavaScript. But now that we have CSS3 supported well by all the major browsers, we can animate our sites with just CSS.

    Animations were supported in AngularJS in version 1.1.5 beta. It underwent a number of changes before a stable version of the feature was released in AngularJS 1.2. Animation support in an Angular application can be added or removed very easily. The library brings very good support for both CSS based and JavaScript based animations. Though animations can be written in JavaScript, it is recommended to use CSS animations. This is because CSS animations are treated with low priority by the browser, and they don’t block the processing thread when the thread could be doing something important.

    In this article, we will see how CSS animations can be used to make the behavior of built-in directives of AngularJS attractive. Going through the capabilities of animations supported in CSS is beyond the scope of this article. You can refer to the CSS channel on SitePoint to learn more.

    Getting Started

    To use animations, we need to include the angular-animate.js library and add the module ngAnimate as a dependency in the module, as shown below.

    [js]
    angular.module(‘coursesApp’, ['ngAnimate']);
    [/js]

    The library adds animation support to the following directives on the specified events:

    Directives Events
    ng-view
    ng-include
    ng-switch
    ng-if
    enter
    leave
    ng-repeat enter
    leave
    move
    ng-show
    ng-hide
    ng-class
    add
    remove

    These events are generated automatically when there is any change in the state of the directives. The important thing to remember is, these events are generated only when the module ngAnimate is passed as a dependency in the application module. When these events are fired, they add CSS classes on the applied element. The corresponding names of the CSS classes are mentioned in the above table. As you can see, we are given liberty to define behavior when the event is happening and also after the event has happened.

    Animating ng-view

    When a user navigates from one view to another, the routing is resolved on the client side and a portion of the page is loaded with new content. This happens really fast and sometimes the user may feel that the change in the view is too spontaneous. An animation in this step would make the transition smoother.

    Referring to the above table, we see that ng-view raises two events when the view is changing. Let’s apply the following style when the view is changing.

  3. Creating Charting Directives Using AngularJS and D3.js

    D3 is a JavaScript library that can be used to create interactive charts with the HTML5 technology Scalable Vector Graphics (SVG). Working directly with SVG to create charts can be painful, as one needs to remember the shapes supported by SVG and make several calls to the API to make the chart dynamic. D3 abstracts most of the pain, and provides a simple interface to build SVG-based charts. Jay Raj published two nice SitePoint articles on working with D3, check them out if you are not already familiar with D3.

    Most of you may not need a formal introduction to AngularJS. AngularJS is a client side JavaScript framework for building rich web applications. One of the top selling points of AngularJS is the support for directives. Directives provide an excellent way to define our own HTML properties and elements. It also helps in keeping the markup and code separated from each other.

    AngularJS is very strong in data binding as well. This feature saves a lot of time and effort required to update the UI according to data in the model. In the modern web world, customers ask developers to build websites that respond in real-time. This means the customers want to always see the latest data on the screen. Data UI has to be updated as soon as someone modifies a piece of data in the back-end. Performing such real-time updates would be very difficult and inefficient if we don’t have support of data binding.

    In this article, we will see how to build real-time AngularJS directives that wrap D3 charts.

    Setting Up

    First, we need to set up the environment. We need AngularJS and D3 included in the HTML page. As we will build just a chart directive, we need to create an AngularJS controller and a directive. In the controller, we need a collection holding data to be plotted in the chart. The following snippet shows the initial controller and directive. We will add more code to these components later.

    [js]
    var app = angular.module(“chartApp”, []);

    app.controller(“SalesController”, ["$scope", function($scope) {
    $scope.salesData = [
    {hour: 1,sales: 54},
    {hour: 2,sales: 66},
    {hour: 3,sales: 77},
    {hour: 4,sales: 70},
    {hour: 5,sales: 60},
    {hour: 6,sales: 63},
    {hour: 7,sales: 55},
    {hour: 8,sales: 47},
    {hour: 9,sales: 55},
    {hour: 10,sales: 30}
    ];
    }]);

    app.directive(“linearChart”, function($window) {
    return{
    restrict: “EA”,
    template: ““,
    link: function(scope, elem, attrs){
    }
    };
    });
    [/js]

    We will fill the link function in the above directive to use the data stored in the controller and plot a line chart using D3. The template of the directive contains an svg element. We will apply D3′s API on this element to get the chart plotted. The following snippet shows an example usage of the directive:

    [html]

    [/html]

    Now, let’s gather the basic data needed for plotting the chart. It includes the data to be plotted, JavaScript object of the SVG element, and other static data.

    [js]
    var salesDataToPlot=scope[attrs.chartData];
    var padding = 20;
    var pathClass = “path”;
    var xScale, yScale, xAxisGen, yAxisGen, lineFun;

    var d3 = $window.d3;
    var rawSvg = elem.find(“svg”)[0];
    var svg = d3.select(rawSvg);
    [/js]

    Once the library for d3 is loaded, the d3 object is available as a global variable. But, if we use it directly inside a code block, it is hard to test that block of code. To make the directive testable, I am using the object through $window.

    Drawing a Simple Line Chart

    Let’s set up the parameters needed to draw the chart. The chart needs an x-axis, a y-axis, and the domain of data to be represented by these axes. In this example, the x-axis denotes time in hours. We can take the first and last values in the array. On the y-axis, the possible values are from zero to the maximum value of sales. The maximum sales value can be found using d3.max(). The range of the axes vary according to the height and width of the svg element.

  4. Implementing Authentication in Angular Applications

    Authentication and authorization are important pieces on almost every serious application. Single Page Applications (SPAs) are no exception. The application may not expose all of its data and functionality to just any user. Users may have to authenticate themselves to see certain portions of the application, or to perform certain action on the application. To identify the user in the application, we need get the user logged in.

    There is a difference in the way user management is implemented in traditional server-driven applications and Single Page Applications. The only way in which an SPA can interact with its server components is through AJAX. This is true even for logging in and logging out.

    The server responsible for identifying the user has to expose an authentication endpoint. The SPA will send the credentials entered by the user to this endpoint to for verification. In a typical token based authentication system, the service may respond with an access token or with an object containing the name and role of the logged in user after validating the credentials. The client has to use this access token in all secured API requests made to the server.

    As the access token will be used multiple times, it is better to store it on the client side. In Angular, we can store the value in a service or a value as they are singleton objects on the client side. But, if the user refreshes the page, the value in the service or value would be lost. In such case, it is better to store the token using one of the persistence mechanisms offered by the browser; preferably sessionStorage, as it is cleared once the browser is closed.

    Implementing Login

    Let’s have a look at some code now. Assume that we have all server side logic implemented and the service exposes a REST endpoint at /api/login to check login credentials and return an access token. Let’s write a simple service that performs the login action by hitting the authentication endpoint. We will add more functionality to this service later:

    [js]
    app.factory(“authenticationSvc”, function($http, $q, $window) {
    var userInfo;

    function login(userName, password) {
    var deferred = $q.defer();

    $http.post(“/api/login”, {
    userName: userName,
    password: password
    }).then(function(result) {
    userInfo = {
    accessToken: result.data.access_token,
    userName: result.data.userName
    };
    $window.sessionStorage["userInfo"] = JSON.stringify(userInfo);
    deferred.resolve(userInfo);
    }, function(error) {
    deferred.reject(error);
    });

    return deferred.promise;
    }

    return {
    login: login
    };
    });
    [/js]

    In actual code, you may want to re-factor the statement storing data to sessionStorage into a separate service, as this service gets multiple responsibilities if we do this. I am leaving it in the same service to keep the demo simple. This service can be consumed by a controller that handles the login functionality for the application.

    Securing Routes

    We may have a set of secured routes in the application. If a user is not logged in and attempts to enter one of those routes, the user should be directed to the login page. This can be achieved using the resolve block in the routing options. The following snippet gives an idea on the implementation: