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.