If you’re building a large Angular app it’s only a matter of time before you will want your parent and child controllers to talk to each other in response to events.

A simple example is when you may use a global controller and controllers for specific views.

Below is a simple example:

index.html

app.js

partials/login.html

In this simple example the loginCtrl handles the login state and is nested within the appCtrl which handles the wider application.

If you want to communicate an event from the loginCtrl to the appCtrl, like the success of a login event, when you would use $emit.

js/controllers/loginCtrl.js

You can listen for the event using $on in the appCtrl.

js/appCtrl.js

If you want to go the other way, from the appCtrl to the loginCtrl then you would use $broadcast in the appCtrl and $on in the loginCtrl.

js/appCtrl.js

js/controllers/loginCtrl.js

To summarise the usage:

$broadcast(name, args);
$emit(name, args);
$on(name, listener);

The event listener function format is: function(event, args).

Developers who don’t fully understand inheritance tend to use $rootScope instead since data stored in $rootScope is available app wide. This can be ok, in the case of user details that are potentially required app wide, but can be a big problem in other contexts.

 

 

Tristan Claridge on EmailTristan Claridge on LinkedinTristan Claridge on Twitter
Tristan Claridge
Web Developer at Claridge Media
Tristan is a full stack developer with over 10 years experience developing innovative projects using LAMP, jQuery, AngularJS, NodeJS, and others. He has started and operated a variety of businesses including building the software systems used by, or sold by, the businesses. Tristan grew up in Brisbane, Australia, and has a couple of degrees from the University of Queensland. Tristan now lives in Dunedin, New Zealand, enjoying world-class internet speeds and the beautiful country.