- controllerAs View Syntax: Use the controllerAs syntax over the classic controller with the $ scope syntax.
Why ?: The controllers are built, "innovated" up and provide one new instance, and the controllerAs syntax is closer to the JavaScript constructor syntax than the classic $ scope syntax.
Why? This facilitates the use of binding to the "punctuated" object in the view (for example, customer.name instead of the name), which is more contextual, easier to read, and avoids any problems with the link that may occur without "arranging".
Why ?: Helps to avoid using $ parent calls in views with nested controllers.
<div ng-controller="Customer"> {{ name }} </div> <div ng-controller="Customer as customer"> {{ customer.name }} </div>
- controllerAs Controller syntax: use controllerAs syntax over a classic controller with $ scope syntax.
The controllerAs syntax uses these internal controllers that are tied to $ scope
Why ?: controllerAs is syntactic sugar for $ scope. You can still get attached to the View tools and still access the $ scope methods.
Why ?: It helps to avoid the temptation to use the $ scope methods inside the controller when otherwise it is better to avoid them or move them to the factory. Consider using $ scope in the factory, or if in the controller, when necessary. For example, when publishing and subscribing to events using $ emit, $ broadcast or $ on, it is recommended to move these uses to the factory and call from the controller.
function Customer ($scope) { $scope.name = {}; $scope.sendMessage = function () { }; } function Customer () { this.name = {}; this.sendMessage = function () { }; }
- controllerAs with vm: use the capture variable for this when using the controllerAs syntax. Select a constant variable name, such as vm, which means ViewModel.
Why ?: This keyword is contextual and, when used inside a function inside a controller, can change its context. Capturing the context of this avoids this problem.
function Customer () { this.name = {}; this.sendMessage = function () { }; } function Customer () { var vm = this; vm.name = {}; vm.sendMessage = function () { }; }
Note. You can avoid any jshint warnings by posting a comment below the line of code. / * jshint validthis: true / var vm = this; Note. When creating a watch in a controller using a controller, you can watch vm. member using the following syntax. (Create watches with caution as they add more load to the digest cycle.)
$scope.$watch('vm.title', function(current, original) { $log.info('vm.title was %s', original); $log.info('vm.title is now %s', current); });
https://github.com/johnpapa/angularjs-styleguide#controllers