简体   繁体   中英

Calling a function in a parent directive from child directive

I have a child directive called dropDownSortMenu . An element within this child directive has a ng-click function. Upon execution of this function, I want to call a function of the parent directive customTable .

The plnkr is located here: http://plnkr.co/edit/7b2mce9jsAXmJpfKjgdx

I think you were already very close to using the correct approach. You already had a controller present, but there were two things missing:

  1. The sort function needs to be set on the parent directive controller's context. (ie this )
  2. Then you need to require: '^customTable' . (the ^ is used to denote we are looking for a controller on a parent directive).

Now in dropDownSortMenu 's link function, you have access to the parent controller's context and can do anything you please.

Demo

Use the scope's event dispatchers ; $emit(name, args) is used to send an event up to parent scopes, and $broadcast(name, args) will sink events downwards through the hierarchy.
To catch thrown events use $on(name, listener) listeners.

You could just as well refer to $scope.$parent to travel up the chain (or $scope.$parent.$parent etc.), but this is not recommended - you will have to look up the scope hierarchy n levels up, rendering that code rigid (what if you change the scope nesting level, eg by adding an ng-repeat somewhere?).


You can also utilize transclusion in the directive (when appropriate) - which will allow your model to reside outside the directive's isolated scope, thus allowing natural access to any controller in the hierarchy above (provided that no isolated scope is in the way).
See $compile service docs for an explanation on the directives' tranclude property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM