gpt4 book ai didi

Angularjs:将所需的指令 Controller 注入(inject) Controller 而不是链接函数

转载 作者:行者123 更新时间:2023-12-02 21:53:06 24 4
gpt4 key购买 nike

Angular 中的正常用例

如果您有父指令和子指令,您可以在父指令的 Controller 中创建方法,并在子指令中需要父 Controller 。 Angular 会将父 Controller 传递到您的子指令链接函数中。

我的用例

我有一个用例,其中子指令是另一个指令的父指令。我在顶部有一个指令,这是中间指令所要求的。底部的最后一个指令需要中间的指令。

在一个简单的世界中,我可以为中间指令创建一个链接方法和一个 Controller 。 link 方法使用顶部 Controller 处理所有内容,并将中间 Controller 传递给底部指令。

就我而言,中间指令的 Controller 中的方法必须调用父级中的方法,因此我需要中间 Controller 中的顶部 Controller ,而不是中间指令的链接函数中的顶部 Controller !

问题

如何将所需的 Controller 而不是链接函数注入(inject)到 Controller 中

angular.module('app').directive('top', function () {
return {
$scope: true,
templateUrl: "top.html",
controller: function() {
this.topMethod = function() {
// do something on top
}
}
}
});

angular.module('app').directive('middle', function () {
return {
$scope: true,
templateUrl: "middle.html",
require: "^top",
controller: function($scope, $attrs, topController) {
this.middleMethod = function() {
// do something in the middle

// call something in top controller, this is the part that makes everything so complicated
topController.topMethod();
}
}
}
});

angular.module('app').directive('bottom', function () {
return {
$scope: true,
templateUrl: "bottom.html",
require: "^middle",
link: function(scope, element, attrs, middleController) {
$scope.bottomMethod = function() {
// do something at the bottom

// call something in the parent controller
middleController.middleMethod();
}
}
}
});

最佳答案

实际上还有另一种更简洁的方法 is used by the angular ngModel itself :

var parentForm = $element.inheritedData('$formController') || ....

基本上,它们利用了 Controller 存储在指令 dom 元素的 data 属性中的事实。

仍然有点连贯,但更简洁,更容易理解。

我不明白为什么您无法将所需的 Controller 传递到指令 Controller 的注入(inject)局部变量中。

关于Angularjs:将所需的指令 Controller 注入(inject) Controller 而不是链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com