我有几个分层指令,其中一个指令的 Controller 中需要有一些函数,以便子元素可以与其交互。但是这个指令还需要引用其父指令的 Controller ,但我不知道如何在 Controller 中执行此操作(我知道如何在“link()”中执行此操作,但这次我需要 Controller 用于子交互)。应该可以在范围内做到这一点:
controller: function($scope){},
link: function (scope, ..., parentCtrl){
scope.parentCtrl = parentCtrl;
}
但这看起来很奇怪,因为链接函数是在 Controller 之后执行的,或者它可以吗?我很困惑,我认为这可能是一个糟糕的设计?
图表:
ParentParentDirective
controller: function(service){
this.service = service;
}
ParentDirective
controller: function(){
this.callOnService = function(id){
???ParentParentDirective???.service.callSth(id);
}
}
ChildDirective
link(scope, ...,ParentDirectiveCtrl){
scope.makeChanges = ParentDirectiveCtrl.callOnService;
}
最佳答案
您可以使用 $element.controller 方法,如下例所示。
angular.module('app', []);
angular.module('app').directive('grandparent', function () {
return {
restrict: 'E',
controller: function () {
this.go = function () {
console.log('Grandparent directive');
};
}
};
});
angular.module('app').directive('parent', function () {
return {
restrict: 'E',
controller: function () {
this.go = function () {
console.log('Parent directive');
};
}
};
});
angular.module('app').directive('child', function () {
return {
restrict: 'E',
require: ['^parent', '^grandparent'],
controller: function ($element) {
var parentCtrl = $element.controller('parent');
var grandparentCtrl = $element.controller('grandparent');
parentCtrl.go();
grandparentCtrl.go();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="app">
<grandparent>
<parent>
<child></child>
</parent>
</grandparent>
</div>
关于javascript - 将父指令的 Controller 传递给指令 Controller (就像在 "link"函数中完成的那样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503106/