Access parent controller in angular directive

回眸只為那壹抹淺笑 提交于 2019-12-12 04:56:54

问题


having same nested directives:

<div mydir="a">
  <div mydir="b">
  </div>
</div>

if mydir requires ?^mydir it always get itself's controller.
test_plunk
is it possible to access parent's controller?


回答1:


According the angular documentation on jqLite, you can call controller() to retrieve the controller for any given element:

controller(name) - retrieves the controller of the current element or its parent. By default retrieves controller associated with the ngController directive. If name is provided as camelCase directive name, then the controller for this directive will be retrieved (e.g. 'ngModel').

Within your link function, you can retrieve the parent controller by calling controller() on the parent element and passing in the name of the directive:

var parentCtrl = iElement.parent().controller('mydir');



回答2:


$scope.$parent.a;

shall give you a

$scope is the scope injected by angular

$parent is a keyword reference to the parent scope from any scope in angular.

Yes this is JavaScript, and as was asked in the question, AngularJS powered Javascript



来源:https://stackoverflow.com/questions/24240782/access-parent-controller-in-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!