Last Updated: September 09, 2019
·
30.41K
· 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 () {
  return{
    restrict: "A",
    require:['^parentDirective', '^ngModel'], 
    link: function ($scope, $element, $attrs, controllersArr) {

      // parentDirective controller
      controllersArr[0].someMethodCall(); 

      // ngModel controller         
      controllersArr[1].$setViewValue(); 
    }
  }
});

Here is an example of it in action:
Example

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: https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1223

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, https://coderwall.com/p/14rwpg

<small>I had a little help from this post http://www.bennadel.com/blog/2447-Exploring-Directive-Controllers-Compiling-Linking-And-Priority-In-AngularJS.htm</small>

over 1 year ago ·

would suggest you to check this site - www.careerbaba.in

Very helpful.

over 1 year ago ·