AngularJS Directive-Controller Two Way Communication

How to communicate between AngularJS Directive & Controller without using $broadcast?

We as developers usually come across situations where we have to call a method defined in the AngularJS Directive from the Controller or vice versa.

The easy way out will be to use $broadcast on the $scope or the $rootScope, which work’s quite well. But overusing $broadcast becomes kind of an anti pattern and may lead to performance issues and as the app becomes larger you may not know from where all the calls are going out.

Here’s how I would go about it:

I have a CustomerService which has two methods

  1. get: Fetches the list of customer by calling a Web API & return’s a promise.
  2. save: Save’s a customer by passing the customer to the Web API & return’s a promise.​

Then a controller called CustomerController.

As you can see there is an object called accessor which is defined on the $scope, this object will be bound to the addCustomer directive which will attach saveCustomer function to the object & the controller can call that function.

In this controller’s view we display the list of customers & we have a modal which has the addCustomer directive inside it.

So basically what I want to achieve is that on click of saveCustomer() button of the modal, The ‘accessor’ object’s method will be called which post’s the customer object to the Web API & return’s a promise after which the custom list will be refreshed.

The directive AddCustomerDirective definition & it’s template markup.

This pattern can also be used the other way around i.e. communicating with the controller from the directive.