Tobias J.
Tobias J.

Reputation: 1053

AngularJS - How to get directive-controller in directive with "require"

I have a directive with a require. Now I want to get the required controller instance AND the controller of the directive in the link function. How is that possible? If i set 'require' the fourth parameter of the link function only contains the required controller. If I do not set the requirement the fourth parameter of the link function contains the controller of the directive. How to get both?

Upvotes: 1

Views: 212

Answers (1)

gkalpak
gkalpak

Reputation: 48212

You should require both, then the 4th argument will be an array of controllers (in the same order as the required directives.

E.g. from the source code of Angular's ngModel directive (which needs access to both NgModelController and its wrapping form's FormController):

var ngModelDirective = function() {
    return {
        require: ['ngModel', '^?form'],
        controller: NgModelController,
        link: function (scope, elem, attrs, ctrls) {
            ...
            var modelCtrl = ctrls[0],
                formCtrl  = ctrls[1] || nullFormCtrl;
            ...

Upvotes: 2

Related Questions