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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With