AngularJS: Communicate Among Controllers

Working with AngularJS has made things very easy for front-end developers. We can handle almost everything with Controllers.

Parent-Child Controllers

There are times when we needed to work with more than one controllers and we need to communicate between those controllers. It would be easy to communicate between controllers if they are in parent-child relation.

Independent Controllers

In case the controllers are independent and we need to pass information on an event of one controller to another. In this case we can use $on & $broadcast with $rootScope.

What we want to do is get the value from the input text from eventController and show it against the “Name” in listenController. As we can see they are in different controllers so we cannot just display input’s value on “Name“. We need something to interact between those controllers.

Listen Event

First, we need to modify the listenController to listen an event which would happen on the eventController. As the event will occure on different controller we cannot use the $scope but AngularJS gives us ability to listen for and emit event on any module by injecting $rootScope in our controller.

By using $rootScope & $on we can listen any event which may broadcast on any controller on $rootScope. Let’s update our listenController to listen the event.