AngularJS指令控制器需要家长指令控制器? [英] AngularJS directive controllers requiring parent directive controllers?
问题描述
我可能会考虑这件事完全倒退,但我试图让三个嵌套指令,让我们称他们为:显示屏,组件和部件。我想小部件能够引发一些组件的行为,进而触发屏幕一些行为。所以:
I might be thinking about this completely backwards, but I'm trying to make three nested directives, lets call them: screen, component and widget. I want widget to be able to trigger some behavior in component, which in turn triggers some behavior in screen. So:
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
controller: function() {
this.componentFunction = function() {
WHAT.doSomethingScreeny();
}
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
我可以要求一个部件的链接父组件使用FN 要求:^组件
,但我怎么给进一步的组件控制器访问包含它的屏幕?
I can require parent components in a widget's link fn using require: "^component"
, but how do I further give components controller access to its containing screen?
我需要的是什么成分,所以当你单击窗口小部件的按钮,它会提醒screeny!
What I need is the WHAT in component so when you click the widget's button it alerts "screeny!".
感谢。
推荐答案
有两种方法可以解决你的问题:
Here are two ways you could solve your problem:
- 由于您使用的
范围:真正的
,所有范围中典型继承。所以,如果你定义的$范围方法
,而不是在这个
在屏幕
控制器,那么这两个组件
和小部件
将有机会获得功能doSomethingScreeny
。
结果小提琴。 - 定义的
组件
和链接功能要求:^屏
。在链接功能,screenCtrl保存到一个scope属性,那么您可以在指令的控制器访问它(注$范围
)。
结果小提琴。
- Since you are using
scope: true
, all scopes prototypically inherit. So if you define your methods on$scope
instead of onthis
in thescreen
controller, then bothcomponent
andwidget
will have access to functiondoSomethingScreeny
.
Fiddle. - Define a link function on
component
andrequire: '^screen'
. In the link function, save the screenCtrl to a scope property, then you can access it in the directive's controller (inject$scope
).
Fiddle.
这篇关于AngularJS指令控制器需要家长指令控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!