Using "ControllerAs"
= Allows to create named scope on the controller.
Ex. : <div ng-app="app" ng-controller="AnimalCtrl as animal"> <div>
= Instead of defining variables or functions on the $scope, we define it on “this” within the controller function. $scope can be avoided.
Ex.: app.controller("AnimalCtrl", function(){
this.survive= function(){
alert("breathe");
};
});
};
});
= Can be used to share data between controllers.
Similar ways of sharing data between controllers:
1. Using Services. [The most preferred way compared to the other below ways]
2. Using events
3. Using $parent, nextSibling, etc. to directly access the controllers
4. Using the $rootScope to add the data on (not a good practice)
3. Using $parent, nextSibling, etc. to directly access the controllers
4. Using the $rootScope to add the data on (not a good practice)
Usage of "controllerAs"
1. No need to use $scope in your controller;
<div ng-controller="MainController as main">
{{ main.someProp }}
</div>
app.controller('MainController', function () {
this.someProp = 'Some value.'
// the above is equal to $scope.MainController = this; this.someProp = 'Some value.'
});
2. Can share data between two controllers; the values in both the text boxes update as we change either the child controller text or parent controller text box.
<div ng-controller="ParentController as parent">
ParentController: <input type="text" ng-model="parent.foo" />
parent.foo: {{ parent.foo }}
<div ng-controller="ChildController as child">
ChildController: <input type="text" ng-model="parent.foo" />
parent.foo: {{ parent.foo }}
</div>
</div>
app
.controller('ParentController', function () {
this.foo = "bar";
})
.controller('ChildController', function () { /*empty*/ });
No comments:
Post a Comment