控制器实例存储在哪里?

时间:2014-04-09 10:00:12

标签: angularjs

如果我使用ng-controller将控制器添加到DOM元素,那么存储的结果控制器实例在哪里?

是否添加为DOM元素的属性?

1 个答案:

答案 0 :(得分:3)

是的,它们存储在DOM元素上。 AngularJS使用the element API (aka JqLite)data()方法来存储控制器。

我已经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";
   }
}

是的,您也可以使用

访问它
angular.element('...').controller()

但是你不需要Batarang。它是the element API的一部分。这是获取访问权限的首选方式(或者您可以使用require属性创建指令)。

BTW,范围也以这种方式存储,因此您可以通过

访问它
element.data('$scope')
相关问题