Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


In AngularJS, routes can be defined during the application's configuration
phase using the $routeProvider service. The syntax used by the $routeProvider
service is similar to the one we were playing with in our custom $location
based implementation:


angular.module('routing_basics', [])
.config(function($routeProvider) {
$routeProvider
.when('/admin/users/list', {templateUrl: 'tpls/users/list.
html'})
.when('/admin/users/new', {templateUrl: 'tpls/users/new.html'})
.when('admin/users/:id', {templateUrl: 'tpls/users/edit.html'})

.otherwise({redirectTo: '/admin/users/list'});
})

The $routeProvider service exposes a fluent-style API, where we can chain
method invocations for defining new routes (when) and setting up a default
route (otherwise).


Once initialized, an application can't be reconfigured to support
additional routes (or remove existing ones). This is linked to the fact
that AngularJS providers can be injected and manipulated only in
configuration blocks executed during the application's bootstrap.

In the previous examples, you can see that templateUrl was the only property
for each route but the syntax offered by the $routeProvider service is far richer.


The content of a route can be also specified inline using the
template property of a route definition object. While this is a
supported syntax, hardcoding the route's markup in its definition is
not very flexible (nor maintainable) so it is rarely used in practice.

Displaying the matched route's content

When one of the routes is matched against a URL, we can display the route's
contents (defined as templateUrl or template) by using the ng-view directive.
The $location-based version of the markup looked before as follows:


<div class="container-fluid" ng-include="selectedRoute.templateUrl">
<!-- Route-dependent content goes here -->
</div>
Free download pdf