正常使用情况下角Angularjs:注入所需的指令控制器到控制器,而不是链接功能
如果你有父母的指令,并创建子指令,在父指令的控制器的方法和在你的子指令中需要父控制器。 Angular会将父控制器传递给你的子指令链接函数。
我的使用情况
我有一个使用情况下孩子的指令是另一指令父。我在中间的指令要求的顶部有指令。中间指令是底部最后一个指令所要求的。
在一个简单的世界中,我可以为中间指令创建一个链接方法和一个控制器。链接方法处理所有与顶部控制器和中间控制器传递到底部指令。
在我的情况下,中间指令的控制器中的方法必须调用父项中的方法,所以我需要中间控制器中的顶层控制器,而不是中间指令的链接函数!
问题
我怎么能注入所需的控制器到控制器,而不是链接功能
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();
}
}
}
});
我想你可能已经链接到了错误的jsFiddle。这只是一个你好世界的例子。 – rob
看来,还有更简单的方法如何实现这一点: var parentForm = $ element.controller('form') – romario333
我已经为此和romario333的解决方案添加了一个演示:http://work.karlhorky。 com/frontend-tricks/angular-1-inject-required-directive-controller-into-directive-controller/ –