How to broadcast events in AngularJS

Sometimes you may need to communicate within 2 or more AngularJS components and probably you should use the events. Let’s see how to broadcast events in AngularJS and how to receive them.

Broadcast events in AngularJS

If you want to broadcast use the $rootScope:

$scope.broadcastMyEvent = function() { 

Receiving events in AngularJS

And then to receive, use the $scope of your controller:

$scope.$on('my-cool-event', function(event) { 
  // whatever 

Adding parameters

If you want you can pass any parameter when you $broadcast:

$rootScope.$broadcast('my-cool-event', { hello: { day: 1 } });

And then receive them:

$scope.$on('my-cool-event', function(event, params) { 
  var hello = params.hello; 
  // whatever 

Note you can use as parameter any Javascript object.

You can learn more about it reading the official documentation about $rootScope.

Leave a comment with your doubt or experience! 🙂

David Burgos

Read more posts by this author.