In Angular $scope
is the glue between the Controller and the View that helps with all of our data binding needs. Controller As is another way of binding controller and view and is mostly recommended to use. Basically these are the two controller constructs in Angular (i.e $scope and Controller As).
Different ways of using Controller As are -
controllerAs View Syntax
<div ng-controller="CustomerController as customer">
{{ customer.name }}
</div>
controllerAs Controller Syntax
function CustomerController() {
this.name = {};
this.sendMessage = function() { };
}
controllerAs with vm
function CustomerController() {
/*jshint validthis: true */
var vm = this;
vm.name = {};
vm.sendMessage = function() { };
}
controllerAs
is syntactic sugar over $scope
. You can still bind to the View and still access $scope
methods. Using controllerAs
, is one of the best practices suggested by the angular core team. There are many reason for this, few of them are -
$scope
is exposing the members from the controller to the view via an intermediary object. By setting this.*
, we can expose just what we want to expose from the controller to the view. It also follow the standard JavaScript way of using this.
using controllerAs
syntax, we have more readable code and the parent property can be accessed using the alias name of the parent controller instead of using the $parent
syntax.
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".
Helps avoid using $parent
calls in Views with nested controllers.
Use a capture variable for this when using the controllerAs
syntax. Choose a consistent variable name such as vm
, which stands for ViewModel. Because, 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.
NOTE: using controllerAs
syntax add to current scope reference to current controller, so it available as field
<div ng-controller="Controller as vm>...</div>
vm
is available as $scope.vm
.