Last Updated: September 09, 2019
· pjh

AngularJS: Including multiple controllers in a directive.

Ever needed to require multiple controllers into a single directive?

Say you needed to call a method in a parent directive, but you still need to set the model value from within your directive. To do this you can set the 'require' property in the directive to an array of controllers, then when you pass in a single controller argument to your linking function, you can access each controller in the array by using its array index.

app.directive('myDirective', function () {
    restrict: "A",
    require:['^parentDirective', '^ngModel'], 
    link: function ($scope, $element, $attrs, controllersArr) {

      // parentDirective controller

      // ngModel controller         

Here is an example of it in action:

6 Responses
Add your response

Why would I do such thing? I can't think of any use cases here and when I think of testing, it doesn't seem to be very maintainable (but I'm sure I'm wrong somewhere). Could you give me some examples?

over 1 year ago ·

@paprikkastudio Commonly when forms or form elements are being used. Since ngModel's controller api provides services for data-binding, validation, CSS updates, value formatting and parsing. A directive could require the ngModel controller for validation of an input while also needing to call a method in its parent directives controller.

Here's an example of it being used in the Angular source code:

over 1 year ago ·

I accidentally skipped the part of the documentation that says that "require" could be an array of strings. Very useful to access a dropdown controller to close it and the table controller to get the needed info. Thanks for the snnipet!

over 1 year ago ·

Great, i'm glad it helped!

over 1 year ago ·

Nice, this is handy, but I ended up needing to investigate how to include the directives own controller (custom controller) in addition to required dependencies. Here are my findings,

<small>I had a little help from this post</small>

over 1 year ago ·

would suggest you to check this site -

Very helpful.

over 1 year ago ·