[英]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.