简体   繁体   中英

Pass parent directive's controller to a directive controller (like it is done in the "link" function)

I have several hierarchical directives and in one, I need to have some functions in its controller, so that the child elements can interact with it. But this one directive also needs to reference its parent directive's controller, but I don't know how to do that in controller (I know how in the "link()" but this time I need controller for the child interaction). It should be possible to do it with scope:

controller: function($scope){},
link: function (scope, ..., parentCtrl){
    scope.parentCtrl = parentCtrl;
}

but it seems weird, because the link function is executed after the controller is, or it it OK? I'm confused and I think it might be a bad design?

diagram:

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;
    }

You can use $element.controller method for that, as in example below.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM