JumpStart Angular : Routing

We have seen various aspects of angular to build a dynamic and model binding website. In this post we will look into a very important aspect of any website, called routing. We will look into angular services dealing with route, route parameters etc.

Deep Linking

In world wide web, deep linking represents an url which always points to a single resource. Deep linking helps in indexed and searchable url. e.g. http://www.example.com/home represents home pagehttp://www.example.com/about represents about page etc. But javascript XHttpRequest (ajax request) violates deep linking. Because it changes the content without changing the url. Deep linked urls helps in bookmarking any web content, maintaining browser history and search engine optimization. Read more..

Routing

A route represents an searchable url. e.g. http://www.example.com/products/5 will give details of product with id 5. Routing is the concept of redirecting to appropriate url and display appropriate data. With ajax, we can have a url like  http://www.example.com and on click of login link replace the page content with login form. There can be two scenarios with this,
  1. Url is unchanged:
    This means both the content have same url. So url becomes ambiguous. It will adversely impact the search engines. User will not be able to bookmark his favorite page. 
  2. Url is changed:
    This means url is changed based on the content. Where as the idle approach should be content should change based on url. 
Routing allows you to change the content based on the url, so that you can assure that the url will always give you same result. Angular brings best of both , it specifies urls for each page and updates the section dynamically with out reloading the page.

$routeProvider

$routeProvider is used to configure routes for an application. It has two methods when and otherwise.
when(path,params), path: string, params: object
path contains the route url and named parameters. e.g. in the path /products/:id id is a named parameter, it will match urls like /products/5 or /products/apple. A named parameter is identified with a " : " symbol.
params is an object which contains following properties,
  • controller – {(string|function()} : controller or name of controller.
  • controllerAs – {string} : exposes the controller with specified name.
  • template – {string|function()} : string or function returning string that act as template.
  • templateUrl - {string|function()} : path or function returning path to a html template url.
  • resolve - {Object.<string, function>} : additional dependencies to be passed to the controller.
  • redirectTo – {(string|function())} : url or function returning url to redirect.
  • [reloadOnSearch=true] - {boolean} : reload the route $location.search() or $location.hash() changes.
  • [caseInsensitiveMatch=false] - {boolean} : if true will match the case insensitive route.  
otherwise(params), params: object
Route is always configured for application. We can use config method of application module to configure route. We need to inject $routeProvider and call above two methods to configure route.
var myApp = angular.module("MyApp", []).config([
    '$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/demo1', { templateUrl: 'Demo1/demo.html' }).
            when('/demo2', { templateUrl: 'Demo2/demo.html', controller: calcCtrl }).
            otherwise({ redirectTo: '/demo1' })
}]);

ngView

ngView directive specifies the placeholder for the template. When current location matches any route, routeProvider will get the template, compile it using the controller scope and update the innerHtml of ngView with the compiled html. ngView can be specified as tag , attribute or class name. There can be only one ng-view in a page.
<ng-view></ng-view> or <div ng-view></div> or <div class="ng-view"></div>

$templateCache

$templateCache is an angular service that caches the template content for fast retrieval. When routeProvider will match current location with a route, it gets the template and save it to template cache. Further request to same route will be served from this cache. Angular provides a way to add template directly to the $templateCache. For this we need to use a script tag with type "text/ng-template" and provide an id for the template. This id should match the templateUrl defined in the route. $templateCache provides two methods get and put to access the template via java script.
<script type="text/ng-template" id="home.html">
  WelCome
</script>
------- or -------
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('home.html', 'WelCome');
});
To retrieve we can use ng-include directive or $templateCache.get(). $routeProvider also calls $templateCache to update ng-view.
<div ng-include="home.html"></div>
------- or -------
$templateCache.get('home.html')
In the following example i have defined few routes and templates. I have injected $route service to display current route information.

$routeParams

We have seen how can we redirect to specific route and load coresponding content. In many of the scenarios we need to pass named parameters to route and display the result based on it. e.g http://www.example.com/products/5 will give me product 5 details and http://www.example.com/products/6 will result in product 6 details. $routeParams service is used to access these named parameters. In the below example book1,book2 and book3 has same route but with different named paramter 'id'. On click of Book1, i am reading the id value in route and populate the scope.book object with appropriate data.

How angular routing works?

Angular route is always relative to current route. 
  1. Angular watches for url change and triggers locationChange event
  2. Now $routeProvider will try to match the current url with defined routes and load appropriate template from $templateCache.
  3. Then it compiles the template with the controller scope.
  4. Then it loads the compiled template to ng-view section of page.
  5. if $routeParams is injected, $routeParams will parse the url and stores the parameters as key,value pair.
There are two low level services $route & $location, that provides more information or controller over route and url. $routeProvider and $routeParams internally uses these services to expose related functionality. Using $route we can get information about current route, its controller, scope etc. using $location we can get current url, change url or change some parameters. If we change the url using $location.path('newurl'), it will trigger a location change event and above steps will occur. Following example shows various uses of these services.
For any query/comment/complement please use the comment section or drop me a mail @ [email protected]