Angular JS directive communication guide – part 1

This article was posted by Michał Dudak on 2014-09-21 in Angular JS

The internet is loaded with tutorials and posts about simpler cases of directive-to-directive communication in AngularJS. However, I haven’t found the complete guide covering the less obvious scenarios as well, so here’s my shot at it.

The first part will cover cases where directives are placed on the same element and where the caller is below the callee in the DOM structure. The next one will focus on callers above callees and highlight several problems with transclusion.

Two directives on a single element

This is the simplest case. The directives have three ways of communication: by requiring a controller, by events and by sharing attributes.

Requiring a controller

This case is covered by the API reference and can be thought of as the canonical one. One of the directives publishes an API on a controller and the other consumes it in its link function:

See the full example on JSBin.

Events

Events are perfect if low coupling between directives is needed. Since the two directives use the same scope, it doesn’t really matter whether we use $emit or $broadcast. More info about events can be found in the Angular docs.

See the full example on JSBin.

Sharing attributes

The attributes object (the third parameter of the link function) is shared among all the directives placed on an element. This allows us to pass data from one directive to the other one.

See the full example on JSBin.

Accessing a directive on a parent element

Probably the equally common and supported case – the directive we want to call is above in the DOM hierarchy.

In this case we have two possibilities – we can either require a controller or use events.

Requiring a controller

This is very similar to the previous example.  The only part we need to change is to tell Angular to look for the required directive among parent elements by prepending the require value with the ^ character.

See the full example on JSBin.

Events

The safest way to go in this case would be to $emit an event from the client directive. $broadcast could also work if the client did not create its own scope, but $emit will always be a correct solution.

Note that in this example I’m using the compile function returning the pre-link function instead of more common post-link function. This is because the client’s post-link would fire before the server’s one and emit an event which would not be caught. Server’s pre-link, on the other hand, will be executed before client’s post-link allowing the event to be handled appropriately.

See the full example on JSBin.

Conclusion

These were the most common cases of directive-to-directive communication. In the next post, I’ll explain what to do in more complicated scenarios.

2 comments

  1. Rajesh says:

    Excellent post !!! Very very useful. Great

Leave a Reply

Your email address will not be published. Required fields are marked *