4th argument of the communication function

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

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

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

Now I decided to make the directive more flexible, reusable, etc. So, for directory configuration, I added

 require: '?ngModel' 

Suddenly, my controller is never transferred to the communication function. There is no array for the fourth argument, there is no fifth argument, nada.

I tried adding a controller to the require directive, but it still doesn't find it.

How to add require and pass the controller?

+6
source share
1 answer

require means that the required directive ( ngModelController in this case) will have its own controller sent as the fourth argument to the bind function. The default controller is a directive whose calling function is called the controller, but requires that other directives redefine it (even if this is an optional requirement and the required directive is absent, in this 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 controller var ngModelController = controllers[1]; } }; }); 

Plunker

+8
source

Source: https://habr.com/ru/post/984970/


All Articles