Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent directive's controller recursively in AngularJS

Tags:

angularjs

I need to get parent's controller, so my directive has a require property, as follows:

module.directive('tag', function () {
    return {
        require: '?^tag',
        restrict: 'E',
        controller: function () {
            this.payload = getPayload();
        },
        link: function (scope, element, attrs, ctrl) {
            usePayload(ctrl.payload);
        }
    };
});

However the ctrl parameter of the link function returns the controller of the current directive, not the parent's one. AngularJS documentation is clear about this:

?^ - Attempt to locate the required controller by searching the element's parents, or return null if not found.

What am I doing wrong?

like image 475
Herman Kan Avatar asked Dec 25 '22 19:12

Herman Kan


1 Answers

Either the docs or the code are misleading here... require with ^ looks at the current element and then all parent, using the inheritedData method (see https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L942). So you won't be able to require a directive with the same name from a parent using this approach.

When I've had this issue in the past I've looked at the form directive which needs to do what you are asking. Its controller method grabs the parent like so (https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js#L39):

controller: function($element) {
    var parentForm = $element.parent().controller('form');
}

Taking this, you should be able to call element.parent().controller('tag') to find the parent controller either in the controller or postLink methods.

like image 111
Andyrooger Avatar answered Jun 09 '23 08:06

Andyrooger