Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


Mapping routes to URLs

Having a simple routing structure in place isn't enough. We need to synchronize the
active route with the current URL. We can do this easily, by watching the path()
component of the current URL as follows:


$scope.$watch(function () {
return $location.path();
}, function (newPath) {
$scope.selectedRoute = routes[newPath] || defaultRoute;
});

Here, each change in $location.path() component will trigger a lookup for one
of the defined routes. If a URL is recognized, a corresponding route becomes the
selected one. Otherwise, we fall back to a default route.


Defining controllers in route partials

When a route is matched, a corresponding template (partial) is loaded, and included
into the page by the ng-include directive. As you remember the ng-include
directive creates a new scope, and most of the time we need to set up this scope with
some data that make sense for the newly loaded partial: a list of users, a user to be
edited, and so on.


In AngularJS, setting up a scope with data and behavior is the job the controller. We
need to find a way to define a controller for each and every partial. Obviously, the
simplest approach is to use the ng-controller directive in the root element of each
partial. For example, a partial responsible for editing users would look as follows:


<div ng-controller="EditUserCtrl">
<h1>Edit user</h1>
...
</div>

The downside of this approach is that we can't reuse the same partial with different
controllers. There are cases where it would be beneficial to have exactly the same
HTML markup, and only change the behavior and the data set up behind this partial.
One example of such a situation is an edit form, where we would like to reuse the
same form both for adding new items editing an existing item. In this situation the
form's markup could be exactly the same but data and behavior slightly different.

Free download pdf