Skip to content

Route provider decorators

Jens Melgaard edited this page Jul 29, 2013 · 4 revisions

Decorators allow you to make changes to the route object before the $routeChangeSuccess event is raised. But not before the $routeChangeStart or $routeUpdate events.

This is to avoid running decorators on routes that are just redirects or has already been decorated.

Since decorators is properly a really rare scenario, they are not covered in detail here. Instead lets take a look at how we use a decorator to provide the backwards compatibly for the new $routeProvider

angular.module('dotjem.routing.legacy', ['dotjem.routing', 'ng']).config([
    '$routeProvider',
    function ($routeProvider) {
        $routeProvider.decorate('templateDecorator',
            ['$q', '$injector', '$templateCache', '$http',
    function ($q,   $injector,   $templateCache,   $http) {
            var next = this,
                values = [],
                keys = [],
                template;

            angular.forEach(next.resolve || {}, function (value, key) {
                keys.push(key);
                values.push(angular.isString(value) ?
                    $injector.get(value) :
                    $injector.invoke(value));
            });
            if (angular.isDefined(template = next.template)) {
                if (angular.isFunction(template)) {
                    template = template(next.params);
                }
            } else if (angular.isDefined(template = next.templateUrl)) {
                if (angular.isFunction(template)) {
                    template = template(next.params);
                }
                if (angular.isDefined(template)) {
                    next.loadedTemplateUrl = template;
                    template = $http.get(template, {
                        cache: $templateCache
                    }).then(function (response) {
                        return response.data;
                    });
                }
            }
            if (angular.isDefined(template)) {
                keys.push('$template');
                values.push(template);
            }
            return $q.all(values).then(function (values) {
                var locals = {
                };
                angular.forEach(values, function (value, index) {
                    locals[keys[index]] = value;
                });
                return locals;
            }).then(function (locals) {
                next.locals = locals;
            });
        }]);
    }]);
Clone this wiki locally