需要父指令控制器的AngularJS指令控制器?

发布于 2021-02-01 10:21:18

我可能会考虑将其完全倒退,但是我正在尝试制作三个嵌套指令,让它们称为:屏幕,组件和小部件。我希望窗口小部件能够触发组件中的某些行为,从而触发屏幕中的某些行为。所以:

.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中要求父组件require: "^component",但是如何进一步使组件控制器访问其包含的屏幕呢?

我需要的是WHAT in组件,因此,当您单击小部件的按钮时,它会发出“ screeny!”警报。

谢谢。

关注者
0
被浏览
83
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    您可以通过以下两种方式解决问题:

    1. 由于您正在使用scope: true,所有作用域都原型继承。所以,如果你确定你的方法$scope,而不是对thisscreen控制器,那么两个componentwidget可以访问功能doSomethingScreeny
      小提琴

    2. component和上定义链接函数require: '^screen'。在链接功能中,将screenCtrl保存到scope属性,然后可以在指令的控制器(inject $scope)中访问它。
      小提琴



推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看