Interaction between nested directives

AngularJS provides a useful structure that allows you to build channels of communication between directive siblings (within the same HTML element) or parents in the same DOM ancestry without having to rely on AngularJS events.

Getting ready

For this recipe, suppose that your application template includes the following:

(index.html)

<div ng-app="myApp">
  <div parent-directive>
    <div child-directive 
         sibling-directive>
    </div>
  </div>
</div>

How to do it…

Inter-directive communication is accomplished with the require attribute, as follows:

return {
  require: ['^parentDirective', '^siblingDirective'],
  link: function (scope, el, attrs, ctrls) {
    $log.log(ctrls);
    // logs array of in-order required controller objects
  }
};

Using ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.