Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

4th argument to the link function

I have a directive written by another developer that basically has following configuration:

{
    controller: MyController,
    controllerAs: 'myController',
    link: function(scope, $element, attrs, ctrl) {
        // Does some setup that requires controller
    }
}

This works fine, controller is passed as fourth argument, directive works.

Now I decided to make the directive more flexible, reusable and stuff. So, to directive configuration I added

require: '?ngModel'

Suddenly, now my controller is never passed to a link function. There is no array for the fourth argument, there's no fifth argument, nada.

I tried adding controller to require directive - but it still does not find it.

How do I add require and pass the controller?

like image 236
Eugene Avatar asked Apr 11 '15 00:04

Eugene


1 Answers

require means that the directive you required (ngModelController in this case) will have its controller sent as the fourth argument of the linking function. The default controller is the directive's, whose linking function is called, controller but requiring another directives overrides it (even if it's an optional requirement and the required directive isn't present, in which case the fourth argument will be undefined). Fortunately, require can be an array of directives, so this will work:

module.directive('myDirective', function() {
    return {
        controller: MyController,
        controllerAs: 'myController',
        require: ['myDirective', '?ngModel'],
        link: function(scope, $element, attrs, controllers) {
            var MyDirectiveController = controllers[0]; //this directive's controller 
            var ngModelController = controllers[1];
        }
    };
});

PLUNKER

like image 58
Mosho Avatar answered Nov 14 '22 21:11

Mosho