Category Archives: Routing

AngularJs Routes

AngularJS routes enable you to create different URLs for different content in your application. A route is specified in the URL after the # sign.

As shown below:

http://angularjsapp.com/index.html#users

When browser loads application it bydefault goes to index.html but angularJs looks at routes and decides which template to show.

Routing in AngularJs:

1. Include AngularJs Route Module:

We need to include AngularJs Route Module if routing is to be done.

<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js”></script>

2. Declare dependency on Route Module:

Application needs to declare dependency on route module in order to use ngRoute module.

var module = angular.module(“sampleApp”, ['ngRoute']);

3.  ngView Directive:

Use ngView inside <div>, so that template specific to route will be displayed here.

<div ng-view></div>

4. Configure $routeProvider:

The $routeProvider is what creates the $route service. By configuring the$routeProvider before the $route service is created we can set what routes should result in what HTML templates being displayed. As shown below:

module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: 'template-1.jsp',
controller: 'UserController'
}).
otherwise({
redirectTo: '/'
});
}]);

The when() function takes a route path and a JavaScript object as parameters.

The otherwise() function takes a JavaScript object. It tells AngularJS what it should do if no route paths matches the given URL.

5. Provide Links to Routes:

Provide links to route as shown below :

<a href=”#/route1“>Route 1</a><br/>

6. Route paramenters:

We can provide parameters with routes path as shown:

#/users/1

Here, ‘1’ is the parameter passed with route path.

We can read parameters while configuring $routeProvider as shown below:

when(‘/route1/:param‘, {
templateUrl: ‘template-1.jsp’,
controller: ‘RouteController’
})

Controller can get access to params using $routeParams service as shown below:

module.controller(“UserController”, function($scope, $routeParams) {
$scope.param = $routeParams.param;
})

Now, your view can also get access to param as $scope.param is assigned the value of $routeParams.param.


ProsperaSoft offers AngularJs development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft AngularJs experts and consultants.