Wednesday, 27 March 2013

Templates, Routing and Sharing Data Between Views in an Angular JS Application

Till last post, we saw the capabilities of Angular JS within a single page with a form and how to interact with service using AJAX. Another key feature that Angular JS provides is, view composition. We can compose multiple views on the same page, based on some templates which will be loaded as and when they are required. We will discuss about these features in this post.

To make an HTML page able to compose multiple views using AngularJS, we need to add an element with ng-view attribute. Content will be dynamically added inside this element based on certain rules defined by the programmer. Following is the mark-up inside the body tag after removing all content and adding a div with ng-view attribute:

<body ng-app="shopping">
    <div ng-view>
    </div>
</body>

The entire mark-up that we had earlier on the page is moved to AddRemoveItems.htm. No change has been made to the mark-up.
<div>
    Sort by:
    <select ng-model="sortExpression">
        <option value="Name">Name</option>
        <option value="Price">Price</option>
        <option value="Quantity">Quantity</option>
    </select>
</div>
<div>
    <strong>Filter Results</strong></div>
<table>
    <tr>
        <td>
            By Any:
        </td>
        <td>
            <input type="text" ng-model="search.$" />
        </td>
    </tr>
    <tr>
        <td>
            By Name:
        </td>
        <td>
            <input type="text" ng-model="search.Name" />
        </td>
    </tr>
    <tr>
        <td>
            By Price:
        </td>
        <td>
            <input type="text" ng-model="search.Price" />
        </td>
    </tr>
    <tr>
        <td>
            By Quantity:
        </td>
        <td>
            <input type="text" ng-model="search.Quantity" />
        </td>
    </tr>
</table>
<table border="1">
    <thead>
        <tr>
            <td>
                Name
            </td>
            <td>
                Price
            </td>
            <td>
                Quantity
            </td>
            <td>
                Remove
            </td>
        </tr>
    </thead>
    <tbody ng-repeat="item in items | orderBy:mySortFunction | filter: search">
        <tr>
            <td>
                {{item.Name}}
            </td>
            <td>
                {{item.Price | rupee}}
            </td>
            <td>
                {{item.Quantity}}
            </td>
            <td>
                <input type="button" value="Remove" ng-click="removeItem(item.ID)" />
            </td>
        </tr>
    </tbody>
</table>
<div>
    Total Price: {{totalPrice() | rupee}}</div>
<a ng-click="purchase()">Purchase Items</a>
<form name="itemForm" novalidate>
<table>
    <tr>
        <td>
            Name:
        </td>
        <td>
            <input name="name" type="text" ng-model="item.Name" required ng-pattern="name" />
        </td>
    </tr>
    <tr>
        <td>
            Price:
        </td>
        <td>
            <input name="price" type="text" ng-model="item.Price" required valid-price />
        </td>
    </tr>
    <tr>
        <td>
            Quantity:
        </td>
        <td>
            <input name="quantity" type="number" ng-model="item.Quantity" min="1" max="90" ng-pattern="integerval"
                required />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="Button" value="Add" ng-click="addItem(item)" ng-disabled="itemForm.$invalid" />
        </td>
    </tr>
</table>
</form>
<div class="errorText">
    {{error}}</div>
<div ng-show="itemForm.name.$dirty && itemForm.name.$invalid">
    <span ng-show="itemForm.name.$error.required">Name cannot be left blank</span> <span
        ng-show="itemForm.name.$error.pattern">Name cannot contain numbers or special characters</span>
</div>
<div ng-show="itemForm.price.$dirty && itemForm.price.$invalid">
    <span ng-show="itemForm.price.$error.required">Price cannot be blank</span> <span
        ng-show="itemForm.price.$error.validPrice">Price should be a number between 50 and
        5000 with maximum 2 digits after decimal point</span>
</div>
<div ng-show="itemForm.quantity.$dirty && itemForm.quantity.$invalid">
    <span ng-show="itemForm.quantity.$error.required">Quantity cannot be blank</span>
    <span ng-show="itemForm.quantity.$error.pattern || itemForm.quantity.$error.min || itemForm.quantity.$error.max">
        Quantity should be an integer between 1 and 90</span>
</div>

Once a user adds all desired items to the cart, he should be able to check out the cart. For this, we should navigate the user to another page where the user can see the items on the cart and checkout the items. I created another template file, CheckoutItems.htm. This template will be rendered when the user clicks on checkout link on the AddremoveItems page. You can check the template from the project on Github.

The aim is to render one of these templates on the page based on the current URL. To make this happen, we need to configure routes to the module. Process of adding routes is similar to adding routes in Global.asax ASP.NET MVC. Each route will hold the following information:

  • URL template of the page
  • Path of the HTML template to be rendered
  • Name of the controller
Following is the syntax of configuring routes to the module:
module.config([‘$routeProvider’,<other dependencies>, function($routeProvider,<other parameters>){
 $routeProvider.when(‘<url-template>’,{templateUrl:’<path-of-html-template>’,controller:<name-of-controller>})
   .otherwise({redirectTo:’<default-url-template-to-render>’});
}]);

To learn more on routing, refer to Angular JS official documentation.

Let’s configure routes to shopping module keeping the above syntax in mind. Following are the templates added to the module in our application:

shoppingModule.config(['$routeProvider', function($routeProvider){
        $routeProvider.when('/addRemoveItems',{templateUrl:'Templates/AddRemoveItems.htm',controller:ShoppingCartCtrl})
                      .when('/checkoutItems',{templateUrl:'Templates/CheckoutItems.htm',controller:CartCheckoutCtrl})
                      .otherwise({redirectTo: '/addRemoveItems'});
    }]);

In the AddRemoveItems view, we should have a hyper link to navigate to the CheckoutItems page. When the user clicks on this link, we should send shopping cart data to the checkout view. Since both views have separate controllers, we have to store the data at a central place to make it accessible in the controller of second page. Let’s add a service to the shopping module to hold this data.
shoppingModule.service('shared',function(){
        var cartItems= [];
        return{
            getCartItems: function(){
                return cartItems;
            },
            setCartItems: function(value){
                cartItems=value;
            }
        };
    })

On click of the link on the AddRemoveItems page, the data has to be assigned to cartItems field in the above service and the control has to be navigated to checkout view. This is done using the following function:
$scope.purchase = function () {
        shared.setCartItems($scope.items);
        $window.location.href = "#/checkoutItems";
};

$window used in the above function is a service in Angular JS that references to the browser’s window object. Since we are using it in the controller, it should be injected through parameter. This data can be accessed in checkout view using the shared service. Following code shows how to do it:
function CartCheckoutCtrl($scope, shared){
    function loadItems() {
        $scope.items = shared.getCartItems();
    }
 
    loadItems();
}

Now we have a tiny shopping cart application with two pages. This is definitely not a great application, but it covers most of the useful features of Angular JS.

Complete code of the application is available in the following github repo: AngularShopping

Cart Run the application setting ShoppingCart-MultipleViews.htm as the start-up page. Notice the URL once the page is loaded on browser. Click on the link, it should move to the Checkout view, with an update to the URL. You can also switch between the views using browser’s back and forward buttons.

The point to be observed during navigation is, the page is not fully refreshed. You won’t see the progress bar showing load status when the navigation happens. This is because, we are rendering a small part of the page(portion in the div marked with ng-view) using a template.

Happy coding!

Wednesday, 13 March 2013

Moving AJAX calls to a custom service in Angular JS

In my last post on Angular JS, we moved the data into an ASP.NET Web API controller and invoked the data using $http, a service in Angular JS that abstracts AJAX calls. But the code resided in the controller and that is not good. Responsibility of the controller should be to sit between data and view, but not to call services using AJAX. So, let’s move the AJAX calls to a separate component.

The AJAX calls made using $http service are executed asynchronously. They return promise objects, using which their status can be tracked. As we will be moving them into a custom service, the controller depending on them should be notified with the status of completion. The notification can be sent using the promise object returned by the service functions or, we can create our own deferred object using $q service.

I discussed about deferred and promise in jQuery earlier in a post. Basic usage of the pattern remains the same with $q as well, except a small difference syntax. Following snippet is shows the way of creating a deferred object, calling success and failure functions using $q:

function myAsyncFunc(){
//Creating a deferred object
var deferred = $q.defer();
operation().success(function(){
    //Calling resolve of deferred object to execute the success callback
    deferred.resolve(data);
  }).error(function(){
    //Calling reject of deferred object to execute failure callback
    deferred.reject();
  });
  //Returning the corresponding promise object
  return deferred.promise;
}

While calling the above function, a callback to be called on success and a callback to be handled on failure should be attached. It might look as follows:
myAsyncFunction().then(function(data){
    //Update UI using data or use the data to call another service
  },
  function(){
    //Display an error message
  });

The functions responsible for making AJAX calls should follow this pattern as the functions in $http are executed asynchronously. To notify the dependent logic about state of execution of the functionality, we have to use the promise pattern.

As we will be enclosing this functionality in a custom service which requires $http for AJAX and $q for promise, these dependencies will be injected at the runtime when the module is loaded. Following snippet demonstrates the implementation of a function to retrieve items in shopping cart calling Web API service:

angular.module('shopping', []).
  factory('shoppingData',function($http, $q){
    return{
      apiPath:'/api/shoppingCart/',
      getAllItems: function(){
        //Creating a deferred object
        var deferred = $q.defer();

        //Calling Web API to fetch shopping cart items
        $http.get(this.apiPath).success(function(data){
          //Passing data to deferred's resolve function on successful completion
          deferred.resolve(data);
      }).error(function(){

        //Sending a friendly error message in case of failure
        deferred.reject("An error occured while fetching items");
      });

      //Returning the promise object
      return deferred.promise;
    }
  }
}

Following is the controller consuming the above custom service:
function ShoppingCartCtrl($scope, shoppingData) {
  $scope.items = [];

  function refreshItems(){
    shoppingData.getAllItems().then(function(data){
      $scope.items = data;
    },
    function(errorMessage){
      $scope.error=errorMessage;
    });
  };

  refreshItems();
};

As you see parameters of the controller, the second parameter shoppingData will be injected by the dependency injector during runtime. The function refreshItems follows the same convention as the snippet we discussed earlier. It does the following:
  • On successful completion of getAllItems() function, it assigns data to a property of $scope object which will be used to bind data
  • If the execution fails, it assigns the error message to another property of $scope object using which we can display the error message on the screen

The controller is free from any logic other than updating data that is displayed on the UI.

Functions to add a new item and remove an existing item also follow similar pattern. You can find the complete code in the following github repo: AngularShoppingCart

Happy coding!

Friday, 8 March 2013

Understanding Promise Pattern in JavaScript Using jQuery’s Deferred Object

Asynchronous programming is used almost everywhere these days. JavaScript is no exception. In rich JavaScript applications, we have to perform several tasks like calling a service using AJAX, caching data, applying animations and some new cases might arise while writing the application.

Irrespective of whether an operation is synchronous or asynchronous, we need a response from the when the operation is succeeded or even when it fails. Synchronous operations are usually enclosed within try…catch blocks to check for errors. As asynchronous operations run in background and we can’t determine when they will complete, their failures cannot be caught by the catch block. Even in case of successful completion, the response won’t be available for the immediate next statement. These cases are handled using callbacks.

We see several patterns in which callbacks are registered. While using raw AJAX invocations with XMLHttpRequest, we assign the callback to onreadystatechange property of the object, as shown below:

var xhr = new XMLHttpRequest();
xhr.open(“GET”,url, true);
xhr.send();

xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
     successCallback(xhr.responseText);
        }
        else{
            failureCallback(xhr.responseText);
        }
    }
};

We also see the cases where the asynchronous function accepts a callback function as a parameter.
invokingAsyncFunction(successCallback(data), failureCallback(error));

These callbacks look good unless we have a chain of three or more asynchronous calls. When the number goes up, it becomes difficult to handle them and the code becomes less readable.

We can overcome this difficulty using the Promise pattern. The Promise pattern believes in returning a deferred object that can be used to call a piece of logic when the underlying asynchronous operation is either resolved or rejected. In other words, we can say the pattern promises us that it would send a result when it gets. The result can be data if the operation is successful or details of an error in case of failure.

The deferred object will hold the current state of the asynchronous operation. At any given time, the deferred object will have one of the three states: unresolved, resolved and rejected.

The deferred object would be in unresolved state when it is waiting for the asynchronous operation to complete. Once the operation is completed successfully, it enters resolved state. Otherwise, it enters rejected state.

jQuery library added support of deferred in jQuery 1.5. The library itself uses this feature for implementation of AJAX features.

jQuery’s deferred object makes it easy to write asynchronous code in JavaScript. Following steps must be followed while writing an asynchronous function using deferred object:

  1. Get a deferred object by calling the $.Deferred() constructor
  2. In case of success, call resolve function passing result of the operation
  3. In case of failure, call reject function passing the error details
  4. Return deferred’s promise object, which provides ways to attach callbacks and determine current state of the deferred object

With this understanding, let’s put the above AJAX logic in a function and make it asynchronous using jQuery’s deferred object:
function ajaxCallToAUrl(url){
  var deferred = $.Deferred();    //Getting a deferred object
  var xhr = new XMLHttpRequest();

  xhr.open(“GET”,url,true);
  xhr.send();

  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status==200)
        deferred.resolve(xhr.responseText);  //Calling resolve() in case of success
      
      else
        deferred.reject(xhr.responseText);  //Calling reject() in case of failure
    }
  }
  return deferred.promise();  //Returning the promise object
}

Following are the steps to be followed while calling the above function:
  1. Call the function and store the returned promise in an object
  2. Attach a callback to done() function of promise. It will be called when the deferred object enters resolved state
  3. Attach a callback to fail() function of promise. It will be called when the deferred object enters rejected state

Following snippet demonstrates it:
var promise = ajaxCalToAUrl(url);
promise.done(function(data){
    //Update the UI to bind data obtained
}.fail(function(error){
    //Display the error message
});

The success and failure functions can also be attached to the promise object using then function as well. The then() function accepts three callbacks, first one is for success, second one is for failure and the third one is for handling progress. Failure and progress callbacks are optional. Progress callback is executed when deferred receives a progress notification. Above implementation can be expressed as follows using then function:
promise.then(function(data){
    //Update the UI to bind data obtained
}, function(error){
    //Display the error message
}, function(){
    //Notify user that the operation is in progress
});

Using then(), we can chain multiple operations as well. Following snippet demonstrates chaining:
var secondPromise = firstPromise.then(function(data){
    return callAnotherAsyncFunction(data);     //Assuming the function callAnotherAsyncFunction returns a promise
});

secondPromise.done(function(data){
    //Chained request is successful. Update UI with the data obtained
});
We can also combine multiple requests using $.when(). The when() function accepts multiple deferred objects. It returns a promise object. State of the when function changes to resolved when all the operations are successfully completed. If any of the operation is failed, state of when changes to rejected.
$.when(deferred1, deferred2).done(function(){
    //Logic to be executed on successful execution
}).fail(function(){
    //Logic to be executed upon failure of any of the operations
});

This is a beginning to using promises. jQuery's deferred object offers capabilities to forcefully reject the operation, notify change of status and some other features that we may require in an application.

References:


Documentation on jQuery’s official site about deferred objects
Article about deferred and promise on MSDN ScriptJunkie


Happy coding! 

Tuesday, 5 March 2013

AJAX using Angular JS

Angular JS defines a service, $http, that is capable of communicating with remote servers over HTTP using XmlHttpRequest. $http includes a service that takes a single configuration object where we configure all required properties for the remote asynchronous call. Following is the syntax of using $http service with configurations:
$http({method:’<method>’, url: ‘<service-url>’})
 .success(function(data, status, headers, config){
  //Logic to be executed upon successful completion of the request
  //Will be called asynchronousy
 })
 .error(function(data, status, headers, config){
 //Logic to be executed when the request is unsuccessful
 //Will be called asynchronously
});

We also have shortcut methods to send get, post, put, delete, head and JSONP requests. These methods accept URL, config. Post and put methods accept input data also as a parameter. To learn more about these methods and the input parameters, refer to $http service documentation.

 Let’s continue with our shopping cart example which I have used in all earlier posts (Last post in this series is Form validation using Angular JS). I created an ASP.NET Web API controller to operate on the cart items. We have to replace the logic of operating with cart items with AJAX calls to the Web API. I chose Web API to create the services because it makes creation and consumption of HTTP services very easy. If you are new to Web API, checkout Web API content on official ASP.NET website.

Following are the ShoppingCartItem and ShoppingCart classes, these classes are used to define structure of each item and to operate on the current items on the cart respectively.

public class ShoppingCartItem
{
    public int ID { get; set; }
    public string Name { get; set; }
    public float Price { get; set; }
    public int Quantity { get; set; }
}


public class ShoppingCart
{
    static List<ShoppingCartItem> cartItems;

    static ShoppingCart()
    {
        cartItems = new List<ShoppingCartItem>()
        {
            new ShoppingCartItem(){ID=1,Name="Soap",Price=25,Quantity=5},
            new ShoppingCartItem(){ID=2,Name="Shaving cream",Price=30,Quantity=15},
            new ShoppingCartItem(){ID=3,Name="Shampoo",Price=100,Quantity=5}
        };
    }
 
    public void AddCartItem(ShoppingCartItem item)
    {
        int nextID = cartItems.Max(sci => sci.ID) + 1;
        item.ID = nextID;
        cartItems.Add(item);
    }

    public IEnumerable<ShoppingCartItem> GetAllItems()
    {
        return cartItems;
    }

    public void RemoveItem(int id)
    {
        cartItems.RemoveAll(sci => sci.ID == id);
    }
}

In the controller, we just need to invoke the methods defined in the ShoppingCart class. This makes the controller pretty straight forward. Following is the implementation:
public class ShoppingCartController : ApiController
{
    ShoppingCart cart;
 
    public ShoppingCartController()
    {
        cart = new ShoppingCart();
    }
 
    // GET api/<controller>
    public IEnumerable<ShoppingCartItem> Get()
    {
        return cart.GetAllItems();
    }
 
    // POST api/<controller>
    public void Post(ShoppingCartItem item)
    {
        cart.AddCartItem(item);
    }
 
    // DELETE api/<controller>/5
    public HttpResponseMessage Delete(int id)
    {
        cart.RemoveItem(id);
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

As we see, the URI templates to call each of these methods are specified in a comment above each method. For example, to call the get method to obtain all cart items, we will use the following logic:
$http.get('/api/shoppingCart/').success(function (data) {
     $scope.items = data;
    });

I am using the shorthand get method of http service here. We can obtain the same result using $http(options) as well. For the time being, I am placing the logic of AJAX calls in Controller to make the demo simple. We will move it into a module in another post. Following is the modified controller:
function ShoppingCartCtrl($scope, $http) {
 $scope.items = [];

 $scope.item = {};
 
 $scope.sortExpression = "Name";

 function refreshItems(){
  $http.get('/api/shoppingCart/').success(function (data) {
  $scope.items = data;
       });
 };
 
 $scope.addItem = function (item) {
  $http.post('/api/shoppingCart/', item).success(function(){
  refreshItems();
  });
  $scope.item = {};
                $scope.itemForm.$setPristine();
 };
 
 $scope.removeItem = function (id) {
  $http.delete('/api/shoppingCart/'+id).success(function(){
  refreshItems();
  });
 };
 
 $scope.mySortFunction = function(item) {
  if(isNaN(item[$scope.sortExpression]))
   return item[$scope.sortExpression];
  return parseInt(item[$scope.sortExpression]);
 };
 
 $scope.totalPrice = function(){
  var total = 0;
  for(count=0;count<$scope.items.length;count++){
   total += $scope.items[count].Price*$scope.items[count].Quantity;
  }
  return total;
 };
 
 $scope.name=/^[a-zA-Z ]*$/;
  
 $scope.integerval=/^\d*$/;

 refreshItems();
}

 Complete code of the sample is available on this github repo: AngularShoppingCart
I will be adding more code to this repo in the future.

Happy coding!

Thursday, 21 February 2013

Form validation using Angular JS

User input validation is a crucial feature to be implemented in any data driven application. We have a number of libraries that support input validation on client side and all of them address this issue in a very effective way. Since Angular JS is designed to make the process of client side data driven application development easier, it also has a nice support of user input validation.

Angular is capable of validating HTML5 input types like required, url, number and email. It also provides some directives like min, max, minlength, maxlength and required for validation. If any of these built-in features is not able to address the business purpose, we can define our own directive and use it for validation.

To indicate the user about validity of form data, the following CSS classes can be defined. They will be applied to the input fields by Angular JS whenever they are required:


  • ng-valid – Applied if the value satisfies validation rules
  • ng-invalid – Applied if the value doesn’t satisfy validation rules
  • ng-dirty – Applied only when there is change in the value of the field
  • ng-pristine – Applied if the field is untouched

Let’s apply some validations to the shopping cart item form that we have been using in earlier posts. If you didn’t read old posts yet, refer to the jsfiddle sample of the last post. Following are the CSS styles that will be applied on the form elements:

input.ng-invalid.ng-dirty {
 background-color: #FA787E;
}
input.ng-valid.ng-dirty {
 background-color: #78FA89;
}

Let's apply the following validations on the cart item form:

  • All fields are required – can be done using required attribute
  • Item name should contain only alphabets and spaces, quantity should be an integer – can be achieved using pattern directive
  • Price should be a float number with value between 50 and 5000 – can be done using a custom validation (Note: Though it can be achieved using pattern, I am using custom validator for demonstration)
  • Quantity should be an integer with minimum value 1 and maximum value 90 – can be achieved using min and max directives and a regular expression to check for integer

If the browser supports HTML5, browser will also validate the form elements. This behaviour can be supressed using novalidate attribute on the form tag. Following is the mark-up of item form with validation attributes applied:

<form novalidate name="itemForm">
 <table>
  <tr>
   <td>Name: </td>
   <td><input name="name" type="text" ng-model="item.Name" required ng-pattern="name" /></td>
  </tr>
  <tr>
   <td>Price: </td>
   <td><input name="price" type="text" ng-model="item.Price" required  valid-price /></td>
  </tr>
  <tr>
   <td>Quantity: </td>
   <td><input name="quantity" type="number" ng-model="item.Quantity" min="1" max="90" ng-pattern="integerval" required /></td>
  </tr>
  <tr>
   <td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" ng-disabled="itemForm.$invalid" /> </td>
  </tr>
 </table>
</form>

Notice the ng-disabled directive on the button. It is used to disable the button if any of input elements in the form is not valid.

To match the pattern of name and quantity fields, ng-pattern attribute is applied on them. The corresponding patterns have to be assigned to a field in the controller.

$scope.name=/^[a-zA-Z ]*$/;

$scope.integerval=/^\d*$/;

For the custom validation to validate price, a directive with the name validPrice has to be created. Let’s add this directive to the shopping module we created in last post.
angular.module(‘shopping’,[])
 .value(…)
 .filter(…)
 .directive('validPrice',function(){
  return{
   require: "ngModel",
   link: function(scope, elm, attrs, ctrl){
    var regex=/^\d{2,4}(\.\d{1,2})?$/;
    ctrl.$parsers.unshift(function(viewValue){
     var floatValue = parseFloat(viewValue);
     if( floatValue >= 50 && floatValue <=5000 && regex.test(viewValue)){
      ctrl.$setValidity('validPrice',true);
     }
     else{
     ctrl.$setValidity('validPrice',false);
     }
     return viewValue;
    });
   }
  };
 });


With this, we are done with all validations. But this leaves the form in invalid state whenever the input fields are cleared after adding an item to the cart. To prevent this behaviour, we have to manually set the form’s state as pristine. Following statement does this for us:
$scope.itemForm.$setPristine();

This statement has to be added to the addItem function of the controller. Though the validations are doing a great job by indicating the invalidity of data on input fields, the user won’t get to know about what has to be modified unless a friendly message is displayed. Message can be displayed in any format that you like. To keep it simple, I am displaying the messages in span elements. An invalid message should be displayed when both of the following conditions meet:

  • An input field is modified – can be checked using $dirty
  • Contains an invalid value – can be checked using $invalid

Following is the markup for displaying error message:

<div ng-show="itemForm.name.$dirty && itemForm.name.$invalid">
 <span ng-show="itemForm.name.$error.required">Name cannot be left blank</span>
 <span ng-show="itemForm.name.$error.pattern">Name cannot contain numbers or special characters</span>
</div>
<div ng-show="itemForm.price.$dirty && itemForm.price.$invalid">
 <span ng-show="itemForm.price.$error.required">Price cannot be blank</span>
 <span ng-show="itemForm.price.$error.validPrice">Price should be a number between 50 and 5000 with maximum 2 digits after decimal point</span>
</div>
<div ng-show="itemForm.quantity.$dirty && itemForm.quantity.$invalid">
 <span ng-show="itemForm.quantity.$error.required">Quantity cannot be blank</span>
 <span ng-show="itemForm.quantity.$error.pattern || itemForm.quantity.$error.min || itemForm.quantity.$error.max">Quantity should be an integer between 1 and 90</span>
</div>

Carefully examine the ng-show directives applied on the div and span elements. The pattern of each condition is in every ng-show directive is:

<form-name>.<element-name>.$error.<type-of-validation>

If there are multiple conditions for one error message, they have to be combined using AND(&&) or OR(||) depending upon the need.

The complete sample is available at the following jsfiddle:



Further learning:

Happy coding!

Saturday, 16 February 2013

Modules in Angular JS

Angular JS supports modules, using which we can divide the JavaScript code involved in our application. Creating modules not only helps separating the code into individual concerns but also improves unit-testability. The modules can be easily replaced by some mocks while unit testing Angular controllers.

Following is the syntax of creating and registering a module:

angular.module(‘module-name’,[dependencies]);

Every module should have a name, which is specified in the first parameter. Second parameter to module function is an array, which may contain names of other modules or services. If the module doesn’t depend on anything, the array can be left blank.

To a module, we can add services, filters, directives, constants, configuration blocks and run blocks. In large applications, it is recommended to add each of these to separate modules. A typical module with all of these blocks added looks like the following:

angular.module(‘module-name’,[dependencies])
 .value(‘service-name’,{
  //properties and functions to be added to the service
         }).
         filter(‘filter-name’,{
         //definition of filter
         }).
         directive(‘directive-name’,function(parameters){
         //directive definition
         }).
         constant(‘constant-name’,object).
         config(function(injectables){
         //configurations to be applied
         }).
         run(function(injectables){
         //code to kick-start the application
         });

In last two posts, we created a shopping cart with functionalities to add and remove items, calculate total price, sort and filter data present in the cart array. Since controller should play the role of mediator, let’s separate data of shopping cart and operations into a separate module and call these functions from controller wherever we need the functionality to be executed. Following is the module that holds data and performs required operations on the data:
angular.module('shopping',[])
   .value('shopping_cart_operations',{
    items : [
     {Name: "Soap", Price: "25", Quantity: "10"},
     {Name: "Shaving cream", Price: "50", Quantity: "15"},
     {Name: "Shampoo", Price: "100", Quantity: "5"}
     ],

    addItem: function(item){
     this.items.push(item);
    },

    totalPrice: function(){
     var total = 0;
     for(count=0;count<this.items.length;count++){
      total += this.items[count].Price*this.items[count].Quantity;
     }
     return total;
    },

    removeItem: function(index){
     this.items.splice(index,1);
    } 
   });

As controller requires the functions defined in the service shopping_cart_service, it has to be passed as a dependency to the controller. The dependency will be automatically resolved at the run-time from the module.

Angular makes heavy usage of Dependency Injection. As we have already discussed in first post, $scope is a mandatory parameter to the controller, but we didn’t discuss about from where it gets its behaviour. It is a service defined in the library and gets injected into the controller when we refer to it by its exact name. To refer it using some other name, we have to assign the modified names to $inject property in the same sequence in which they have to be passed into the function.

MyController.$inject = [‘$scope’, ‘any_other_service’];

After this, we can define the controller as follows:
function MyController(myScope,otherService){
 //Controller body
}
Here, myScope and otherService will hold the values of $scope and any_other_service respectively. To learn more on dependency injection on Angular JS, you can refer to the official website of Angular JS.

Let’s modify ShoppingCartCtrl to use the shopping module created above.

function ShoppingCartCtrl($scope,shopping_cart_operations)  {
 $scope.items = shopping_cart_operations.items;
 $scope.item = {};

 $scope.addItem = function(item) {
  shopping_cart_operations.addItem(item);
  $scope.item = {}; //clear out item object
 };
    
 $scope.totalPrice = shopping_cart_operations.totalPrice;
  
 $scope.removeItem = function(index){
  shopping_cart_operations.removeItem(index);
 };
  
 $scope.mySortFunction = function(item) {
  if(isNaN(item[$scope.sortExpression]))
   return item[$scope.sortExpression];
  return parseInt(item[$scope.sortExpression]);
 }
}

To make the application work as it used to earlier, we need to apply a small change to the HTML. Name of the module has to be assigned to the ng-app directive. Modify the ng-app declaration in the div element to:
<div ng-app="shopping">
....
</div>

Let’s create a simple filter to display price in rupee format and add it to the above module. Following is the code of the filter:
angular.module(‘shopping’,[])
 .value(…)
 .filter(‘rupee’, function(){
  return function(item){
   return "Rs. "+item+".00";
  }
 });

Using this filter is similar to using currency filter.
<td>{{item.Price | rupee}}</td>

This sample is available on jsfiddle:

Happy coding!

Friday, 8 February 2013

Filtering and Sorting data using Angular JS

In last post, we saw how Angular JS helps us in two-way data binding. As I mentioned earlier, Angular JS offers much more than just data binding. We will explore the filtering and sorting features offered by Angular JS.

Angular has a set of filters defined to display data to the user in certain format. We can create our own filters if we are not happy with any of the existing filter. Check Angular’s official developer guide to know more about what filters offer. In this post we will see the usage of some of the built-in filters.

I continue with the same data as I used in the last post. Here is the Angular JS controller with data that we will use in this post. We will add some members to the controller later in the post:

function ShoppingCartCtrl($scope)  {
  $scope.items = [
   {Name: "Soap", Price: "25", Quantity: "10"},
   {Name: "Shaving cream", Price: "50", Quantity: "15"},
   {Name: "Shampoo", Price: "100", Quantity: "5"}
  ];
}

Filtering
Data in an array can be filtered using Angular JS in two ways.

In one approach, we can filter data irrespective of the attributes. The filter is applied across the data in an array. Following markup shows it:

Search: <input type="text" ng-model="searchText" />

<table border="1">
 <thead>
  <tr>
   <th>Name</th>
   <th>Price</th>
   <th>Quantity</th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="item in items | filter:searchText">
   <td>{{item.Name}}</td>
   <td>{{item.Price}}</td>
   <td>{{item.Quantity}}</td>
  </tr>
 </tbody>
</table>

 Initially, the table will display all items present in the items array. As we type some text in the text box, data in the array will be filtered based on the entered text and the filtered data will immediately appear on the list.

As you observe, we didn’t ask Angular to filter data based on a property. This is a general filter. It is applied across the properties.

To filter data based on a property, we have to make some changes to the filter specified above. Following markup segment shows how to do it:

Search by any: <input type="text" ng-model="search.$" />

Search by name: <input type="text" ng-model="search.Name" />

<table border="1">
    <thead>
     <tr>
      <th>Name</th>
      <th>Price</th>
      <th>Quantity</th>
     </tr>
    </thead>
    <tbody>
     <tr ng-repeat="item in items | filter:search">
      <td>{{item.Name}}</td>
      <td>{{item.Price}}</td>
      <td>{{item.Quantity}}</td>
     </tr>
    </tbody>
   </table>

Text entered in the first text box will be used to filter data irrespective of property; it behaves just as our previous case. But the text entered in the second text box will be used to filter data by name alone.

Since price is a dollar amount, we can display the value with a dollar symbol using currency filter.

<td>{{item.Price | currency}}</td>


Sorting
Data in an array can be sorted based on values of a property. We can do it using the orderBy filter.

Let’s add a drop down list to the above sample and sort data based on the selected property. Following markup demonstrated this:

<div>Sort by: 
        <select ng-model=&quot;sortExpression&quot;>
  <option value="Name">Name</option>
  <option value="Price">Price</option>
  <option value="Quantity">Quantity</option>
 </select>
</div>
<table border="1">
 <thead>
  <tr>
   <th>Name</th>
   <th>Price</th>
   <th>Quantity</th>
  </tr>
 </thead>
 <tbody>
  <tr ng-repeat="item in items | orderBy:sortExpression | filter:search">
   <td>{{item.Name}}</td>
   <td>{{item.Price | currency}}</td>
   <td>{{item.Quantity}}</td>
  </tr>
 </tbody>
</table>

As soon as a property is selected from drop-down, you will see the data in the table displayed is sorted according to that property. Observe the sorting pattern of numeric columns (Price and Quantity). They are sorted like strings, not like numbers. This is the default behaviour of the orderBy filter, as mentioned in the documentation.

This behaviour can be overridden by defining a function. If we return value in the form of integer from this function, orderBy filter will apply numeric sorting. Following function can be used to sort string and integer type values. It has to be added to controller:

$scope.mySortFunction = function(item) {
 if(isNaN(item[$scope.sortExpression]))
  return item[$scope.sortExpression];
 return parseInt(item[$scope.sortExpression]);
}

Replace sortExpression of orderBy filter with mySortFunction to sort Price and Quantity as numbers.
<tr ng-repeat="item in items | orderBy:mySortFunction | filter:search">

The mySortFunction checks if the value passed is a number. If it is not a number, it returns the value as is. Otherwise, it parses the value as integer and returns the value.

You can play with the sample on jsfiddle:
Happy coding!

Friday, 1 February 2013

Easy two-way data binding in HTML pages with Angular JS

The world is gradually drifting from heavy server logic to heavy client logic for web applications. We see a number of client side libraries being released for different purposes almost every day. These libraries help front-end web developers to make their applications rich.

Most of the times, we spend time in creating data driven applications, such as shopping cart, accounts management, exploring items like books, audio or video. Data binding becomes primary responsibility for a developer working on such applications. To exploit data binding on client side, we have several libraries like Angular, Knockout, Backbone, and Ember to make our work easier. These libraries also help us to write clean JavaScript code using one of MV* patterns.

Lately, I started exploring Angular JS. It is a great library. Though this post explains about data binding, Angular JS is capable of doing a lot more. Following is a list of features supported by Angular JS:

  • Data Binding
  • Data Templates
  • Filtering and Sorting
  • Validation
  • Support for AJAX
  • History
  • Routing
  • Modular components
  • Dependency injection
  • Encourages separation and testability

Because of these features, Angular JS makes client side development very easier.

Structure of an application using Angular JS
An application using Angular JS must have following components:

  • Reference to Angular JS library
  • A JavaScript controller containing data or with logic to fetch data

We have to add the ng-app declaration to a portion of the page that uses features of Angular JS. It can be added to a div inside a page wherein we have to use some expressions of Angular JS. If it is needed for the entire page, we have to add the ng-app declaration to the body tag.
<div ng-app>
 <!-- Your markup goes here -->
</div>

A demo showing some data binding features of Angular JS
Let’s create a shopping cart. We will add the features to calculate total price of the cart, adding items to cart and removing items from cart. We have to add this logic to the controller. An Angular JS controller must follow the following conventions:

  • It should be a JavaScript function accepting an argument named $scope
  • All of the model variables and functions should be added to the $scope object
  • Controllers are usually suffixed with Ctrl, but it is not necessary

Following is the controller with the required functionalities added:
function ShoppingCartCtrl($scope)  {
    $scope.items = [
        {Name: "Soap", Price: "25", Quantity: "10"},
        {Name: "Shaving cream", Price: "50", Quantity: "15"},
        {Name: "Shampoo", Price: "100", Quantity: "5"}
    ];

    $scope.addItem = function(item) {
        $scope.items.push(item);
 $scope.item = {};
    }
    
    $scope.totalPrice = function(){
        var total = 0;
 for(count=0;count<$scope.items.length;count++){
     total += $scope.items[count].Price*$scope.items[count].Quantity;
 }
 return total;
    }
  
    $scope.removeItem = function(index){
        $scope.items.splice(index,1);
    }
}

To bind data using members of the controller, we have to specify the controller using ng-controller directive. Ensure that the element containing ng-controller directive is a child of an element declared as ng-app.
<div ng-app>
 <div ng-controller="ShoppingCartCtrl">
  <!-- Your markup goes here -->
</div>
</div>

Let’s display the items added to items array in a table. Let’s also add a button on each row to remove the item. We have to use the following blocks to achieve this:

  • ng-repeat directive to iterate through items
  • Binding controller’s properties using {{}}
  • ng-click directive to bind button click event
  • $index to use current index in an array

Following is the table displaying items:

<table border="1">
    <thead>
 <tr>
  <td>Name</td>
  <td>Price</td>
  <td>Quantity</td>
                <td>Remove Item</td>
 </tr>
    </thead>
    <tbody>
 <tr ng-repeat="item in items">
  <td>{{item.Name}}</td>
  <td>{{item.Price}}</td>
  <td>{{item.Quantity}}</td>
  <td><input type="button" value="Remove" ng-click="removeItem($index)" /></td>
 </tr>
    </tbody>
</table>

Let’s display the total price of cart below this table. For this, we need to call the totalPrice() function of controller.
<div>Total Price: {{totalPrice()}}</div>

Finally, let’s add a form to accept values from user and add the new item to items array. We have to use ng-model directive to automatically add an input field to a property of the controller. Following is the form:
<table>
 <tr>
  <td>Name: </td>
  <td><input type="text" ng-model="item.Name" /></td>
 </tr>
 <tr>
  <td>Price: </td>
  <td><input type="text" ng-model="item.Price" /></td>
 </tr>
 <tr>
  <td>Quantity: </td>
  <td><input type="text" ng-model="item.Quantity" /></td>
 </tr>
 <tr>
  <td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" /> </td>
     
 </tr>
</table>

When we enter something in the text boxes, a property named item is automatically added to $scope. This property is used in the addItem function.

You can play with the sample using the following jsfiddle:



Try removing some items from the table and observe that totalPrice is updated immediately. It also happens when an item is added to the array as well.

As we saw, two-way data binding is made very easy using directives and binding syntax of Angular JS. All we need is a controller with some members in it. We don’t need to invoke any special functions to send notification when something changes in the controller. Everything is available for free to us, all we need to do is follow the conventions.

We will explore other features of Angular JS in future posts.

Happy coding!

Sunday, 20 January 2013

Method overloading in TypeScript

TypeScript is observed as an object oriented language. Because of which we expect it to behave just like any other object oriented program out there. One of the key features of any object oriented language is method overloading. The way TypeScript supports this feature is a bit different.

In TypeScript, we cannot create multiple methods with same name in a class. If we attempt to do it, we get an error saying Duplicate identifier <Method name>. It happens even if the methods are defined by following all the rules of method overloading.

The way to achieve method overloading in TypeScript is we have to define a method with highest parameters and declare the other methods. Following sample demonstrates it:

class MyClass
{
 Display(num?: number,name?: string){
  document.write("x is: "+num.toString()+" and y is: "+name);
 }
 Display(num: number);
 Display(name: string);
 Display();
}

As we see, we have defined a Display method with two null able parameters and declared three Display methods with one or no parameters. This code compiles to following JavaScript:
var MyClass = (function () {
    function MyClass() { }
    MyClass.prototype.Display = function (num, name) {
        document.write("x is: " + num.toString() + " and y is: " + name);
    };
    return MyClass;
})();

Yes, there is just one function named Display. Because, a JavaScript function can be called passing all or less number of parameters. This applies to constructor as well.
class MyClass
{
 num: number;
 name: string;
 
 constructor(x?: number,str?: string){
  this.num=x;
  this.name=str;
 }
 constructor(x: number);
 constructor(str: string);
 constructor();
}

This compiles to:
var MyClass = (function () {
    function MyClass(x, str) {
        this.num = x;
        this.name = str;
    }
    return MyClass;
})();

It is important to note that the parameters that have to be omitted in overloads should be marked as nullable in the concrete method. Otherwise, the parameter becomes mandatory and TypeScript compiler reports an error.

Happy coding!

Thursday, 27 December 2012

Friendly URLs in ASP.NET 4.5 Web Forms


In the recent update of ASP.NET, Microsoft released support for Friendly URLs in ASP.NET Web Forms. It is based on the concept of Routing. But, we don’t need to deal with route table to manually add the routes to be mapped. URLs of the site will be automatically made friendly after invoking when the application starts.

To get started using the Friendly URLs, we need to install the NuGet Package Microsoft.AspNet.FriendlyUrls. The package is not stable yet, so we need to search it in pre-release packages.
























This package adds following files to the web application:
  • Microsoft.AspNet.FriendlyUrls assembly – Contains required set of classes and interfaces
  • Site.Mobile.Master – Master page for mobile devices
  • ViewSwitcher.ascx – A user control that can be used to switch views from desktop view to Mobile view and vice versa
Once Visual Studio finishes installing the NuGet package, a read me file will be popped up. This file contains the steps to be followed to enable Friendly URLs on your site. All you have to do is, call the EnableFriendlyUrls extension method of RouteTable in RegisterRoutes method of RouteConfig class. This method is defined in Microsoft.AspNet.FriendlyUrls namespace.
routes.EnableFriendlyUrls();

And make sure that the RegisterRoutes method is called in Application_Start event of Global.asax:
RouteConfig.RegisterRoutes(RouteTable.Routes);

Now run the application and check URL on the address bar of your browser.































And the magic happened! As we see here, the URL doesn’t contain extension of the page.

Note: You don’t have to install NuGet package and apply the above settings if you have installed ASP.NET and Web Tools 2012.2. These changes are built into the ASP.NET web application template in the new template.

If you are using default ASP.NET 4.5 Web application template, you can invoke the Login (which resides in Account folder) page using:

http://mysite/Account/Login

You can link any page that resides in a folder using the same convention.

Hyperlinks to the pages can be replaced with the friendly convention.

<a id="loginLink" runat="server" href="~/Account/Login">Log in</a>

Data can be passed to a page using segments. Href method of FriendlyUrl class can be used for this purpose:
<a href="<%: FriendlyUrl.Href("~/BookDetails","AspNet") %>">ASP.NET</a>

This hyperlink forms the following URL:

http://mysite/BookDetails/AspNet

This data can be displayed on the page in any mark-up element. To display the topic of book sent through the above URL in a span element, we have to get the value from the segment as shown below:

<span><%: Request.GetFriendlyUrlSegments()[0].ToString() %></span>

Also, this value can be passed as a parameter to a method used for Model Binding as shown below:
public IQueryable<Customer> GetBooks([FriendlyUrlSegments]string topic)
{
    var selectedBooks = context.Books.Where(c => c.BookName.Contains(topic));
    return selectedBooks;
}

Remember that, if you are navigating to the page ListBooks.aspx with following URL,

http://mysite/ListBooks/Book/AspNet

then the parameter marked with FriendlyUrlSegments will hold the value Book/AspNet. So, this should be handled with care.

You can also create mobile friendly pages and even pages specific to certain type of device using Friendly URLs. Check Scott Hanselman’s great post on Introducing ASP.NET FriendlyUrls - cleaner URLs, easier Routing, and Mobile Views for ASP.NET Web Forms to learn more
about Friendly URLs and mobile pages.

Happy coding!