Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


Defining default routes

The default route can be configured by calling the otherwise method, providing
a definition of a default, catch-all route. Please notice that the otherwise method
doesn't require any URL to be specified as there can be only one default route.


A default route usually redirects to one of the already defined routes
using the redirectTo property of the route definition object.

The default route will be used in both cases where no path was provided as
well as for cases where an invalid URL (without any matching route) triggers
a route change.


Accessing route parameter values

We saw that route URLs definition can contain variable parts that act as parameters.
When a route is matched against a URL, you can easily access the values of those
parameters using the $routeParams service. In fact, the $routeParams service is a
simple JavaScript object (a hash), where keys represent route parameter names and
values represent strings extracted from the matching URL.


Since $routeParams is a regular service, it can be injected into any object managed
by the AngularJS Dependency Injection system. We can see this in action when
examining an example of a controller (EditUserCtrl) used to update a user's data
(/admin/users/:userid) as follows:


.controller('EditUserCtrl', function($scope, $routeParams, Users){
$scope.user = Users.get({id: $routeParams.userid});

})

The $routeParams service combines parameter values from both the URL's path
as well as from its search parameters. This code would work equally well for a
route defined as /admin/users/edit with a matching URL: /admin/users/
edit?userid=1234.


Reusing partials with different controllers


In the approach taken so far, we defined a controller responsible for initializing
the partial's scope inside each partial using the ng-controller directive. But the
AngularJS routing system makes it possible to define controllers at the route level.
By pulling the controller out of the partial, we are effectively decoupling the partial's
markup from the controller used to initialize the partial's scope.

Free download pdf