[英]Pass parent directive's controller to a directive controller (like it is done in the "link" function)
我有幾個層次指令,其中一個,我需要在它的控制器中有一些函數,以便子元素可以與其交互。 但是這個指令還需要引用其父指令的控制器,但我不知道如何在控制器中執行此操作(我知道如何在“link()”中執行此操作,但這次我需要用於子交互的控制器)。 應該可以在范圍內做到這一點:
controller: function($scope){},
link: function (scope, ..., parentCtrl){
scope.parentCtrl = parentCtrl;
}
但是好像很奇怪,因為link函數是在controller之后執行的,還是這樣就OK了? 我很困惑,我認為這可能是一個糟糕的設計?
圖表:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.