简体   繁体   English

从子指令中调用父指令中的函数

[英]Calling a function in a parent directive from child directive

I have a child directive called dropDownSortMenu . 我有一个名为dropDownSortMenu的子指令。 An element within this child directive has a ng-click function. 此子指令中的元素具有ng-click函数。 Upon execution of this function, I want to call a function of the parent directive customTable . 执行此函数后,我想调用父指令customTable的函数。

The plnkr is located here: http://plnkr.co/edit/7b2mce9jsAXmJpfKjgdx plnkr位于此处: 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. 需要在父指令控制器的上下文中设置sort函数。 (ie this ) (即this
  2. Then you need to require: '^customTable' . 然后,您需要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. 现在,在dropDownSortMenu的链接函数中,您可以访问父控制器的上下文,并且可以做任何您想做的事情。

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. $emit(name, args)用于将事件发送到父作用域,而$broadcast(name, args)将在整个层次结构中向下沉入事件。
To catch thrown events use $on(name, listener) listeners. 要捕获引发的事件,请使用$on(name, listener)监听器。

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?). 你也可以同样参考$scope.$parent向上行进链条(或$scope.$parent.$parent等),但不建议这样 -你将不得不查找范围层次n水平了,使代码僵化(如果您更改范围嵌套级别,例如通过在某处添加ng-repeat怎样?)。


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). 您还可以利用该指令transclusion(适当的时候) -这将使你的模型所在的指令的孤立的范围之内,从而使在上面的层次结构(前提是没有孤立的范围的方式)的任何控制器的自然访问。
See $compile service docs for an explanation on the directives' tranclude property. 有关指令的tranclude属性的说明,请参见$compile服务文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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