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


Setting a default Route


Accessing parameters passed in to Route
Consider we are specifying parameters in the route as shown below

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

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

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
Also we can access Route Params using $route.current.params as

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

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

Access Custom Route Property 
Access Route Param
Access Querystring

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

No comments:

Post a Comment