AngularJS指令控制器需要家长指令控制器? [英] AngularJS directive controllers requiring parent directive controllers?

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

问题描述

我可能会考虑这件事完全倒退,但我试图让三个嵌套指令,让我们称他们为:显示屏,组件和部件。我想小部件能够引发一些组件的行为,进而触发屏幕一些行为。所以:

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:


  1. 由于您使用的范围:真正的,所有范围中典型继承。所以,如果你定义的 $范围方法,而不是在这个屏幕控制器,那么这两个组件小部件将有机会获得功能 doSomethingScreeny
    结果小提琴

  2. 定义的组件和链接功能要求:^屏。在链接功能,screenCtrl保存到一个scope属性,那么您可以在指令的控制器访问它(注 $范围)。
    结果小提琴

  1. Since you are using scope: true, all scopes prototypically inherit. So if you define your methods on $scope instead of on this in the screen controller, then both component and widget will have access to function doSomethingScreeny.
    Fiddle.
  2. Define a link function on component and require: '^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屋!

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