Mastering Web Application

(Rick Simeone) #1
Chapter 6

Once all these route-specific variables (defined in the resolve section) are resolved,
they are injected into the route's controller as follows:


.controller('EditUserCtrl', function($scope, user){
$scope.user = user;
...
})

This is an extremely powerful pattern, as it allows us to define variables that are local
to a given route and have those variables injected into a route's controller. There are
multiple practical applications of this pattern and in the sample SCRUM application
we are using it to reuse the same controller with different values for the user variable
(either created in place or retrieved from a back-end). In the following code snippet, we
can see an extract from the sample SCRUM application:


$routeProvider.when('/admin/users/new', {
templateUrl:'admin/users/users-edit.tpl.html',
controller:'UsersEditCtrl',
resolve:{
user: function (Users) {
return new Users();
}
}
});

$routeProvider.when('/admin/users/:userId', {
templateUrl:'admin/users/users-edit.tpl.html',
controller:'UsersEditCtrl',
resolve:{
user: function ($route, Users) {
return Users.getById($route.current.params.userId);
}
}
});

Defining local variables on a route level (in the resolve section) means that
controllers defined as part of a route can be injected with those local variables.
This greatly improves our ability to unit test the controllers' logic.


Preventing route changes


There are times where we might want to block a route change, based on certain
conditions. For example, consider the following route to edit a user's data:


/users/edit/:userid

Free download pdf