Reputation: 15726
If I add a controller to a DOM element with ng-controller, where is the resulting controller instance stored?
Is it added as a property of the DOM element?
Upvotes: 1
Views: 124
Reputation: 6066
Yes they are stored on the DOM element. AngularJS uses the data()
method of the element API (aka JqLite) to store the controller.
I've made an example on JSFiddle.
myApp.directive('myDirective', function() {
return {
link: function(scope,element) {
scope.name = element.data('$ngControllerController').test();
}
}
});
function MyCtrl($scope) {
this.test = function() {
return "world";
}
}
And yes, you can also access it with
angular.element('...').controller()
But you don't need Batarang for this. It's part of the element API. This is the preferred way of obtaining access (or you can create a directive with a require
attribute).
BTW, the scope is also stored this way, so you can get access to it via
element.data('$scope')
Upvotes: 3