Tuesday, July 29, 2014

Routing in AngularJs


To Start with Routing Demo, Create a page which will act as base page for “Single Page Application”
This page will have <ng-view> element, where our templates will get displayed on our single page.


Templates are simple html markup (without <html>, <body> etc tags) which will get binded with model and get displayed on <ng-view>

Registering a route

$routeProvider service is Used for configuring routes.
$routeProvider has following method used for registering route.
when(route-path, route details);

To Register a route use .config() method of angular module , this method  is run when application is first bootstrapped by angular

angular.module('rountingDemoApp', ['ngRoute'])
.config(function ($routeProvider) {
    $routeProvider.when('/details', {
        templateUrl: 'Templates/ProductList.html',
        controller: 'ProductsController'
    });
});


Specifying parameters in the route

$routeProvider.when('/details/:productID',....)

Setting a default Route

$routeProvider.otherwise({redirectTo:'/details'});

Accessing parameters passed in to Route
Consider we are specifying parameters in the route as shown below
$routeProvider.when('/details/:productID/:orderID',....)

We can use $routeParams service to access the parameters defined in route as follows:
$routeParams.productID
$routeParams.orderID

We can define our custom properties on route while configuring route as shown below
E.g. We are defining myProp as shown below

$routeProvider.when('/details', {
        templateUrl: 'Templates/ProductList.html',
        controller: 'ProductsController',
        myProp:'My Value'
    });

To access this property in controller we will use $route service
$route.current.myProp

Suppose we pass a querystring parameter say myParam(http://localhost:port/#/details?myParam=myval)
To access Querystring parameter we will use $route service as follows
$route.current.params.myParam
Also we can access Route Params using $route.current.params as
$route.current.params.productID

Also we can access Route Params using $route.current.pathParams but we cannot access query string values using pathParams
$route.current.pathParams.productID



To summarize this consider following Scenario
Consider following Route is used to output values
   $routeProvider.when('/details/:productID', {
        templateUrl: 'Templates/ProductList.html',
        controller: 'ProductsController',
        myRouteProp:'This is custom Route Property'
    });

Note Here productID is route parameter and myRouteProp is custom route property
Also consider we are passing following  querystring
http://localhost:port/#/details/2?myQuerystringParam=myval



Access Custom Route Property 
$route.current.PropertyName
Access Route Param
$route.current.params.ParamName
OR
$route.current.pathParams.ParamName
Access Querystring
$route.current.params.myQuerystringParamName



Also we can use $route.reload() method to reload the page without reloading entire application.

Sunday, July 13, 2014

Angular Service



Services in angular are singletons, which are objects that are instantiated only once per app.
Service holds some business logic. Service functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units.

With Services we can achieve following two of SOLID principles
i. Single Responsibility - Single responsibility principle says that every object should have a single responsibility.
So we need to create different services for different responsibilities.
ii.  Dependency Inversion - Dependency Inversion says that objects should depend on abstractions, and not on concrete implementation.
E.g. In C# we can say that our objects should depend on interfaces instead of classes.
This helps to create loosely coupled application and makes unit testing much easier..

Angular services are:
  • Lazily instantiated – Angular only instantiates a service when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
Creating your own Service in Angular

1. Define your service using factory('methodname',function(){}) method of angular.
                This method has two parameters
                i. Name of Service and
                ii. Function which returns the object which represents this service
E.g.
productDemoModule.factory('ProductDataService', function () {
    return {
        getData: function () { return [{ name: 'Product1', price: 100 }, { name: 'Product2', price: 200 }]; },
    }
});


Here i have created a service named , It has a function getData() which returns product details. Currently it returns static data for demo purpose, in your case you can make ajax calls using built in angular services like $http/$resource and retrieve data and return it.

Also you can add required functions and properties similar to getData function and access it later as explained below.


By using the factory method we are registering our service with Angular. This allows Angular’s dependency injection container to inject an instance of our service when we request it in other places.

Using your service
Angularjs provides out of the box support for dependency management.

To use an Angular service, you add it as a dependency for the component (controller, service, filter or directive) that depends on the service. Angular's dependency injection subsystem takes care of the rest.

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

productDemoModule.controller('ProductController', function ($scope, ProductDataService) {
    $scope.products = ProductDataService.getData();   
});

Here we just pass our service as parameter and since we have already registered our service with angular using factory() method shown above angular will inject instance of our service and we don't have to care about instantiating our service. We just simply access functions and properties defined in service.



You can  download code here for this article.

Also i have created a sample code to demonstrate how to use built in services of angular inside our own service. I have demonstrated that using $cookieStore service. You can download this code here.

Also there are other ways to create angular service using service() method or using $provide which i will explain in some other post.

Hope this help you start creating your own service. 

Your comments & feedback will help me to improve my blog :) so feel free to give your comments.

Monday, July 7, 2014

Filters in AngularJS


Filters in AngularJS are used to modify output or format it in required format to be displayed to user.
Angular provide some out of the box filters and it is easy to create our own filter (custom filter).

Filters can be applied to expressions in view templates using the following syntax:
{{ expression | filter }}
 E.g. Following markup formats salary using currency filter.. If salary is 20000 then after applying currency filter result would be #20000.00…In below snipped if we don’t provide currency symbol then default is ‘$’
<div>{{ employeedetails.salary | currency : '#'}}</div>

We can do chaining of filters, means filter can be applied on result of another filter.
{{ expression | filter1 | filter2 | filter3 |... }}

Filter also could have parameters and if it has parameters then those are passed like shown below
{{ expression | filter:parameter1:parameter2:... }}



Creating custom filter

Requirement:  Suppose we have employee designations stored as short forms and we want to show them in full form then we will write a filter which will return full forms for the given short forms.

Solution:
  • Create a filter function on a new module because it is said to be the best practice to define filters inside new module than the existing main application module.

angular.module('myFilterModule', []).filter('DesignationFilter', function () {
    return function (inputVal) {
                switch (inputVal) {
                    case 'TA':
                        return 'Trainee Analyst';
                    case 'JA':
                        return 'Junior Analyst';
                    case 'SA':
                        return 'Senior Analyst';
                    case 'TL':
                        return 'Team Lead';
                    default:
                        return 'Analyst';
                };
            }
})

Here myFilterModule is new module where we have defined our custom filter named ‘DesignationFilter’.

  • Add dependency of this new filter module in our main application module.

var demoApp = angular.module('demoApp', ['ngSanitize', 'myFilterModule']);

  • Use the filter inside expression syntax.

<div>{{employeedetails.designation | DesignationFilter}}</div>



You can Download code here for this article.






Thursday, July 3, 2014

Angular Directives

Angular Directives

Angular 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.

Angular Directives can be written in 4 ways.
1. As a tag e.g . <ng-form />
2. As a attribute of a tag e.g. <div ng-form />
3. As a class e.g. <div class=”ng-form”/>
4. As a html comment
Note: All the directives cannot be written in all 4 ways, refer angular documentation for more details.


  • ng-src :  This attribute is used to provide source of image in <img/> tag
If we have to provide source of image as a value which evaluates at runtime by angular engine (This value contains angular expression) then we use ng-src attribute.

      Consider we have to provide image URL as value which is stored in imageSource property of $scope variable and if we write it as below
<img src=”{{imageSource}}”/>
Then browser immediately tries to render image before angular expression is evaluated, with imageURL as “{{imageSource}}” and which fails.

ng-src attribute delays requesting of image till the time angular replaces angular expression( “{{imageSource }}” in above case ) with actual URL value for the image.



  • ng-repeat : This attribute is used to repeat some template for collection of values.
You can consider this same as foreach loop where you iterate through a collection.

E.g.  <div ng-init="numbers=[1, 2, 3, 4]">
                       <div ng-repeat="n in numbers">
                        {{n}}
                       </div>
        </div>

When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  • When an item is added, a new instance of the template is added to the DOM.
  • When an item is removed, its template instance is removed from the DOM.
  • When items are reordered, their respective templates are reordered in the DOM.
To minimize creation of DOM elements, ngRepeat uses a function to "keep track" of all items in the collection and their corresponding DOM elements. For example, if an item is added to the collection, ngRepeat will know that all other items already have DOM elements, and will not re-render them.
The default tracking function (which tracks items by their identity) does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements.
If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.
For example, you may track items by the index of each item in the collection, using the special scope property $index:
<div ng-repeat="n in [42, 42, 43, 43] track by $index">
  {{n}}
</div>
You may also use arbitrary expressions in track by, including references to custom functions on the scope:
<div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  {{n}}
</div>
  • ng-bind : This attribute is used to bind value to a element.
We use expression syntax to bind value to html elements (eg. <div>Employee Name : {{ employeedetails.firstname }}</div>).
We can do same using the ng-bind directive.
It replaces text content of the HTML element with the value of a given expression, and updates the text content when the value of that expression changes.

E.g. <div ng-bind="employeedetails.firstname"></div>
Please note here that I haven’t used expression syntax(i.e. {{ }}).



  • ng-bind-template : This attribute is used to bind multiple values to a element.
It work same as ng-bind except it can bind multiple values to same element which is not possible with ng-bind.
E.g. <div ng-bind-template="{{employeedetails.firstname}} {{employeedetails.lastname}}"></div>
Please note that here I have to use expression syntax (i.e. {{ }})



  •  ng-bind-html : This attribute is used to bind html string markup to element
It replaces the content(innerHTML) of element with the specified binding.
E.g. For <div ng-bind-html="myhtmlsnippet">My Content</div>
Where $scope.myhtmlsnippet = '<b > <i style="color:red;"> This is Demo created by Naren </i> </b>';

The output for above code snipped would be the “My Content” would be replaced with html in myhtmlsnippet variable.
And the rendered html would be as follows:

<div ng-bind-html="myhtmlsnippet" class="ng-binding"><b> <i> This is Demo created by Naren </i> </b></div>



  • ng-show : This attribute is used to Show or Hide element based on value of binded expression.
E.g. <div ng-show=" myVisibilityParam "></div>

This div will be shown if value of myVisibilityParam variable evaluates to true else it will be hidden.



  • ng-hide : This attribute is used to Hide or Show element based on value of binded expression.
Hides or shows element based on value of binded expression.
E.g. <div ng-hide=" myVisibilityParam "></div>

This div will be hidden if value of myVisibilityParam variable evaluates to true else it will be shown.



  • ng-cloak : This attribute is used to avoid displaying of angular expression tags on slower computer untill they are processed by angular engine.
It holds rendering of html element until the angular directives are processed by angular engine and bindings are replaced with actual values.
If this is not used then user might get flashesh on slower computers and can see binding expressions until then are replaced with actual values..


You can Download code here for this article.

Angular Introduction



Angular.js is a  open source JavaScript library.

Angular uses MVC framework.

Features
  • Angular handles ajax communication with server, and the data is stored in javascript objects.
  • Two way binding -  Two way binding allows updates of the UI automatically whenever data model changes.
  • Routing – handles from moving from one view to another based on user interaction, angular also updates URL of browser.


Passing data to View
$scope – is special object  that angular uses to pass data between controller and view.

Controller and Scope
Primary responsibility of Controller is to create scope object and define the properties/functions on scope object which would be used by View.
Scope communicates with view in two way communication. Hence Data passes from Controller to scope and from scope to View.


Creating Hello world application with angularJS

Following are the steps to create Hellow world application using angularJS.
  1. Add ng-app attribute to html tag - This tells that this html has angular code in it, which would be processed by angular engine.
  2. Define Controller by  defining a javascript function. This controller function would have $scope as parameter. Define properties on $scope variable which would be used to bind data to DOM elements.
  3. In view define a placeholders using “{{ }}” angular expression or angular directives
  4. Tell angular that which element is controlled by which controller using “ng-controller” attribute. Defining ng-controller tells angular that current element and all the child elements will get data from the speicified controller.

Here is my complete code for the Hellow world application

Here is my complete page code. 
Here i have used aspx page you can use html page and put this code in it.
Just you will have to include reference to angular.js library and update its reference in this code as per your library path.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloworldApp.aspx.cs" Inherits="BasicsOfAngular.HelloworldApp" %>


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" ng-app>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1 ng-controller="HelloWorldCtrl">{{HelloWorldMessage}}</h1>
    </div>
     
    </form>
      <script src="Scripts/angular.min.js"></script>
    <script type="text/javascript">
        function HelloWorldCtrl($scope) {
            $scope.HelloWorldMessage = "This is Hello World Demo...";
        }
    </script>
</body>

</html>