Expand Minimize

Use controllerAs in $routeProvider

Use controllerAs in $routeProvider

CheckId NG1050801
TypeName UseControllerAsInRouteProvider
Severity CriticalWarning
Type Route

Using the controllerAs syntax offers the following benefits:

  • it makes obvious which controller you are referring to, when multiple controllers apply to an element
  • if you're writing your controllers as classes, you have easier access to their properties and methods, which will appear on the scope
  • since there is a . in the bindings, you don't have to worry about prototypal inheritance masking primitives

Good practice
angular.module('app').config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: './spa/app/home/home.html',
            controller: 'home',
            controllerAs: 'vm'
        })
        .when('/:id', {
            templateUrl: './spa/app/detail/detail.html',
            controller: 'detail',
            controllerAs: 'vm'
        })
        .otherwise({
                redirectTo: '/'
        });
}]);


Bad practice
angular.module('app').config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: './spa/app/home/home.html',
            controller: 'home'
        })
        .when('/:id', {
            templateUrl: './spa/app/detail/detail.html',
            controller: 'detail'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.