Access parent controller in angular directive

2019-09-03 00:09发布

问题:

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