When creating controllers in AngularJS, the $scope object is very useful and seemingly indispensable. However it is quite possible to avoid using this syntax in most data binding situations. In fact the new AngularJS 2 does not even have a $scope object neither does it have Controllers. Directives have been used instead and the built-in controller method takes on the role of stand alone Controllers. Anyway, I digress, back to the topic of this post.
The Controller as
syntax allows you to refer to the scope using an object literal which can be named appropriately by the developer.
Normally, you would create a Controller like in the code below. (The code is simplified for clarity and Angular set up code has been omitted)
<div ng-controller="parentController"> {{parent.name}} </div>
app.controller('parentController',function(){ $scope.parent = { name: "firtsName" } })
Using the Controller as
approach, allows you to write code as shown below. The $scope
object has been replaced by the keyword this
which refers to the current Controller function’s scope. In Javascript every function creates a closure or scope by default.
<div ng-controller="parentController as parentCtrl"> {{parentCtrl.name}} </div>
app.controller('parentController',function(){ this.parent = { name: "firtsName" } })
One of the major advantages of this approach is that when you have parent and children controllers, you can avoid using $parent
to refer to the parent’s scope in your HTML templates. Imagine you have a complex application with deep nested controllers, it can get pretty confusing having to use several chained $parent
properties as you move up the hierarchy. Instead you can simply refer to the controller you want by name. It is important to note that in such cases you still need the $scope
object in your Javascript code.
<div ng-controller="parentController as parentCtrl"> <p>{{ parentCtrl.name }} </p> <div ng-controller="firstChildController"> <p> {{ parentCtrl.name }} </p> </div> </div>
Leave a Reply