以角度指令访问父控制器 [英] Access parent controller in angular directive

查看:47
本文介绍了以角度指令访问父控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有相同的嵌套指令:

<div mydir="b">

如果 mydir 需要 ?^mydir 它总是得到自己的控制器.
test_plunk
是否可以访问父母的控制器?

解决方案

根据 jqLit​​e 上的 angular 文档,您可以调用 controller() 来检索任何给定元素的控制器:

<块引用>

controller(name) - 检索当前元素或其父元素的控制器.默认情况下检索与 ngController 指令关联的控制器.如果 name 作为camelCase 指令名称提供,则此控制器的控制器指令将被检索(例如'ngModel').

在您的链接函数中,您可以通过在父元素上调用 controller() 并传入指令的名称来检索父控制器:

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

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?

解决方案

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');

这篇关于以角度指令访问父控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆