正常使用情況下角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/ –