Angular's $emit, $broadcast and $on is useful for publish an event and subscribe/unsubscribe to it somewhere else.
Using $scope.$emit will fire an event up the $scope. Using $scope.$broadcast will fire an event down the $scope. Using $scope.$on is how we listen for these events.
// firing an event upwards
$scope.$emit('event:name', 'Hello world');
// firing an event downwards
$scope.$broadcast('event:name', {
msg: 'Hello world!'
});
// listen for the event in the relevant $scope
$scope.$on('event:name', function (event, data) {
console.log(data);
});
The key thing to remember when using $scope to fire your events, is that they will communicate only with immediate parent or child scopes only. But there is one way how to send event to sibling scopes
$scope.$parent.$broadcast('event:name', 'Hello world');
The $rootScope object has the identical $emit, $broadcast, $on methods, but they work slightly differently to how $scope implements them. $rootScope.$emit will fire an event for all $rootScope.$on listeners only, $rootScope.$broadcast will notify all $rootScope.$on as well as $scope.$on listeners.
We can subscribe and unsubscribe event easily
app.controller('TestCtrl', function TestCtrl ($scope) {
// subscribe
var myListener = $scope.$on('event:name', function (event, data) {
// do something
});
// unsubscribe
myListener();
});
If you choose to use $emit, one of your other $scope listeners can cancel it, so prevent it bubbling further. Using $broadcast cannot be cancelled!
Cancelling an event which was sent via $emit looks like this:
$scope.$on('event:name', function (event, data) {
event.stopPropagation();
});