AngularJS Directive Communication Tutorial With Examples

We have discussed about a series of tutorials on custom directives and isolate scope in the previous posts. Sometimes you may want to build a component that is built from a combination of directives. In this post, we are going to discuss this concept and the communication between the nested directives. There are many ways to communicate between directives but in this post, we are going to discuss about the communication that uses controller as an API.

AngularJS Nested Directives

You can create nested directives using the following syntax:

You can also use the following syntax to create the same. In this case we are not replicating the variable and use a dot(.) operator.

AngularJS Directive Communication

Let’s discuss this concept with the following example. In this post, we are going to create three directives  shape , triangle and circle

    • The shapedirective defines a controller with two functions to push values in to the shapes array.
    • The controller will act as an API for other directives which contains the require property.
    • The link function is used to alert the contents in the shapes array when the user clicks on the element. We use jQuery’s bind() method which attaches click event.
    • Then we create directives triangle and circle which contains a link function that calls the method in the shape’s directive controller. You can pass the controller as the fourth parameter. We use the name shapeCtrl in this example. You can choose any name.

  • You may have noticed this line of code in the example, require: '^shape'.  This line is responsible for the communication between the directives.  The ^ prefix means that the directive searches for the controller on its parents.
  • Best Practice: use controller when you want to expose an API to other directives. Otherwise, use link.

Communication Between Directives Example

The following section shows the complete code for the example, which we have explained in this post.
We have defined our custom directives and controller in this script file( app.js).

This is the HTML page we are using in this example to demonstrate the communication between directives.

You will see the following output on your browser.

That’s all for now and you will see more angular features in the coming posts.

By admin

Leave a Reply

%d bloggers like this: