javascript - AngularJS - Why using anonymous controller in directive? -
this source of information:
"the controlleras option enables set controller alias, allowing publish our controller under name , giving scope access controlleras name. step allows reference controller inside view , allows need inject $scope.
this option may seem trivial, in gives lot of power in how can use , create anonymous controllers in our routers , directives. power allows create dynamic objects controllers isolated , easy test.
for instance, can create anonymous controller in directive so:"
var myapp = angular.module("myapp",[]); myapp.directive('mydirective', function(){ return{ restrict: 'a', template: '<h4> {{mycontroller.msg}} </h4>', controlleras: 'mycontroller', controller: function(){ this.msg = "hello world"; } }; });
what functionality of anonymous controllers?
equivalent code without controlleras like:
var myapp = angular.module("myapp",[]); myapp.directive('mydirective', function(){ return{ restrict: 'a', template: '<h4> {{mycontroller.msg}} </h4>', controller: function($scope){ $scope.mycontroller = this; this.msg = "hello world"; }; });
you might use in order introduce better namespacing nested directives. if have parent , child controller, instead of putting property 'name' on scope of each, assign name actual controller (this.name = 'the name') , access these names controllers assigned scope:
myapp.directive('myparentdirective', function(){ return{ restrict: 'a', template: '<div class="parent"><div my-child></div></div>', controlleras: 'parent' controller: function($scope){ this.name = "parent"; }; }).directive('mychilddirective', function(){ return{ restrict: 'a', template: '<div class="child">parent name ="{{ parent.name }}"</div>' + '<div class="child">child name = "{{ child.name }}"</div>', controlleras: 'child' controller: function($scope){ this.name = "child"; }; });
Comments
Post a Comment