8teqba
Last Updated: February 25, 2016
·
27.64K
· pjh
Me

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

Say Thanks
Respond

6 Responses
Add your response

6005
Photo

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 ·
6013
Me

@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 ·
12290
Eightbit 0624941b 2637 4ccb 8fec 0fdd5510964c normal

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 ·
12343
Me

Great, i'm glad it helped!

over 1 year ago ·
12754

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 ·
15245
E750661591fbe0091d448880a5130373 normal

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

Very helpful.

over 1 year ago ·
Awesome Job

Da7871ec 1653 11e8 8f5f 0f6902fdcd42
Web System Analyst
·
Ch√Ęteauguay,Quebec, Canada
·
Full Time