Mastering Web Application

(Rick Simeone) #1

Organizing Navigation


The first approach is the default one. For a route with both the templateUrl and
the controller properties defined, AngularJS will match the route and render the
contents of the partial, even if the data requested by a controller are not ready by this
time. Of course, AngularJS will automatically repaint the partial when the data finally
arrives (and is bound to the scope), but users might notice an unpleasant flickering
effect. The UI flickering happens due to the same partial being rendered twice in a
short timespan, firstly without data and then again when the data are ready.


The AngularJS routing system has excellent, built-in support for the second approach
where the route change (and UI repaint) is postponed until both the partial and all
the requested data are ready. By using the resolve property on a route definition
object we can enumerate asynchronous dependencies for a route's controller.
AngularJS will make sure that all these dependencies are resolved before the route
change (and controller instantiation) takes place.


To illustrate the basic usage of the resolve property, let's rewrite our "edit user" route
as follows:


.when('/admin/users/:userid', {
templateUrl: 'tpls/users/edit.html'
controller: 'EditUserCtrl',
resolve: {
user: function($route, Users) {
return Users.getById($route.current.params.userid);
}
}
})

The resolve property is an object, where keys declare new variables that will be
injected into the route's controller. The values of those variables are provided by
a dedicated function. This function can also have dependencies injected by the
AngularJS DI system. Here we are injecting the $route and Users services to
retrieve and return user's data.


These resolve functions can either return simple JavaScript values, objects, or
promises. When a promise is returned, AngularJS will delay the route change until
the promise is resolved. Similarly if several resolve functions return promises, the
AngularJS routing system will make sure that all the promises are resolved before
proceeding with the route change.


Functions in the resolve section of a route definition can return
promises. The actual route change will take place, if and only if all
the promises are successfully resolved.
Free download pdf