Usage of $broadcast(), $emit() And $on() in AngularJS

I understand that $Broadcast(), $Emit() And $On() are used to raise an event in one controller and handling in another controller. If possible, can someone just give me some real time example on the usage of above three as I am new to angular JS?

I have gone through the following links and understand the basic usage.

2

3 Answers

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):

Demonstrates the method calls:

 $scope.$on('eventEmitedName', function(event, data) ... $scope.broadcastEvent $scope.emitEvent
1
  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.
0

This little example shows how the $rootScope emit a event that will be listen by a children scope in another controller.

(function(){
angular .module('ExampleApp',[]);
angular .module('ExampleApp') .controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) { var vm = this, message = 'Hi my children scope boy'; vm.sayHi = sayHi; function sayHi(){ $rootScope.$broadcast('greeting', message); }
}
angular .module('ExampleApp') .controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) { var vm = this; $scope.$on('greeting', listenGreeting) function listenGreeting($event, message){ alert(['Message received',message].join(' : ')); }
}
})();

The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope and $rootScope.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like