- controllerAs View Syntax: Use the controllerAs syntax over the classic controller with $scope syntax.
Why?: Controllers are constructed, "newed" up, and provide a single new instance, and the controllerAs syntax is closer to that of a JavaScript constructor than the classic $scope syntax.
Why?: It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".
Why?: Helps avoid using $parent calls in Views with nested controllers.
<!-- avoid -->
<div ng-controller="Customer">
{{ name }}
</div>
<!-- recommended -->
<div ng-controller="Customer as customer">
{{ customer.name }}
</div>
- controllerAs Controller Syntax: Use the controllerAs syntax over the classic controller with $scope syntax.
The controllerAs syntax uses this inside controllers which gets bound to $scope
Why?: controllerAs is syntactic sugar over $scope. You can still bind to the View and still access $scope methods.
Why?: Helps avoid the temptation of using $scope methods inside a controller when it may otherwise be better to avoid them or move them to a factory. Consider using $scope in a factory, or if in a controller just when needed. For example when publishing and subscribing events using $emit, $broadcast, or $on consider moving these uses to a factory and invoke from the controller.
/* avoid */
function Customer ($scope) {
$scope.name = {};
$scope.sendMessage = function () { };
}
/* recommended - but see next section */
function Customer () {
this.name = {};
this.sendMessage = function () { };
}
- controllerAs with vm: Use a capture variable for this when using the controllerAs syntax. Choose a consistent variable name such as vm, which stands for ViewModel.
Why?: The this keyword is contextual and when used within a function inside a controller may change its context. Capturing the context of this avoids encountering this problem.
/* avoid */
function Customer () {
this.name = {};
this.sendMessage = function () { };
}
/* recommended */
function Customer () {
var vm = this;
vm.name = {};
vm.sendMessage = function () { };
}
Note: You can avoid any jshint warnings by placing the comment below above the line of code.
/* jshint validthis: true /
var vm = this;
Note: When creating watches in a controller using controller as, you can watch the 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
$scope. It is the recommended way to bind to the UI. For one, without$scopeyou will not$watchand therefore I wouldn't expect 2-way binding to work. Also, your snippets done seem to run for me.