AngularJS $emit $broadcast $on

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:

<body ng-controller="appCtrl">
     <div ui-view id="app"></div>
</body>

index.html

$stateProvider.state('app.login', {
        url: '/login',
        templateUrl: "partials/login.html"
});

app.js

<div class="row" ng-controller="loginCtrl">
    <!-- the login form goes here -->
</div>

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.

// $emit dispatches the event upwards through the scope hierarchy.
$scope.$emit('sendUp', 'going up!');

js/controllers/loginCtrl.js

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

$scope.$on('sendUp', function(event, data) {
        // do something with the data, in this case a string 'going up!'
});

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.

// $broadcast dispatches the event upwards through the scope hierarchy.
$scope.$broadcast('sendDown', 'going down!');

js/appCtrl.js

$scope.$on('sendDown', function(event, data) {
        // do something with the data, in this case a string 'going down!'
});

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.

 

 

Leave a Comment

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

Scroll to Top