简体   繁体   中英

Get parent directive controller in child directive

I have the following directive:

angular.module('test').directive('childDirective', [function() {
    return {
        restrict: 'E',
        require: '^parentDirective',
        controller: function() {
            // How do I get parentDirective's controller?
        },
        link: function($scope, $element, $attrs, $controller) {
            var data = $controller.parentDirectiveData;
            ....
            ....
        }
    };
}]);

In the link function I get $controller dependency that holds a reference to parentDirective's controller. How do I get that reference in childDirective's controller?

You have a couple of options, you can either put it on the scope, or store it in a variable that the controller can access also:

angular.module('test').directive('childDirective', [function() {

    var parentCtrl;

    return {
        restrict: 'E',
        require: '^parentDirective',
        controller: function() {
            // parentCtrl will be defined after the link function runs.
        },
        link: function($scope, $element, $attrs, $controller) {
            var data = $controller.parentDirectiveData;
            parentCtrl = $controller
        }
    };
}]);

Importantly please note that the controller function will run before the link function, so you can only really use this in async callbacks.

There is no way to inject the instance of the parent's controller into the child controller before this, because it relies on the directives being bound to the scope in order for that hierarchy to be defined.

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