AngularJS Angular $scopes Creating custom $scope events


Example

Like normal HTML elements, it is possible for $scopes to have their own events. $scope events can be subscribed to using the following manner:

 $scope.$on('my-event', function(event, args) {
    console.log(args); // { custom: 'data' }
});

If you need unregister an event listener, the $on function will return an unbinding function. To continue with the above example:

var unregisterMyEvent = $scope.$on('my-event', function(event, args) {
    console.log(args); // { custom: 'data' }
    unregisterMyEvent();
});

There are two ways of triggering your own custom $scope event $broadcast and $emit. To notify the parent(s) of a scope of a specific event, use $emit

$scope.$emit('my-event', { custom: 'data' }); 

The above example will trigger any event listeners for my-event on the parent scope and will continue up the scope tree to $rootScope unless a listener calls stopPropagation on the event. Only events triggered with $emit may call stopPropagation

The reverse of $emit is $broadcast, which will trigger any event listeners on all child scopes in the scope tree that are children of the scope that called $broadcast.

$scope.$broadcast('my-event', { custom: 'data' });

Events triggered with $broadcast cannot be canceled.