Use Broadcast, Emit And On in AngularJS

Posted By : Pulkit Chadha | 27-Sep-2017

Introduction:
In angularJs,sometimes we need to communicate between the controllers.This might be needed to send notification or send date to the other controllers.$scope and $rootscope support 3 methods i.e $Broadcast(), $Emit() And $On() for event based communication between the controller.

Overview of $broadcast(), $emit() and $on():-

$broadcast() and $emit() helps to raise an event. The difference between $broadcast() and $emit() is that the $broadcast() sends the event from the current controller to all of its child controllers. The $emit() method sends an event from current controller to all of its parent controllers.

Syntax:

* $scope.$broadcast("Event_Name",data);
* $scope.$emit("Event_Name",data); 
        

An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. 

Syntax:

* $scope.$on("Event_Name", function(event,data){ 
  // handler code here 
});
  

Event system on $scope and $rootScope:-

1) Nested controller or when there is parent-child relationship between the controller.we use $broadcast(), $emit() and $on() on the $scope object.
2) Sibling controller or when there is no relation between the controller.we use $broadcast(), $emit() and $on() on the $rootScope object.

Example of $broadcast and $on:

var app=angular.module('MyApp',[]);

app.controller('ParentCtrl',function($scope){

$scope.$broadcast('ClickEvent',"Hello Angular");

});

app.controller('childCtrl',function($scope){

$scope.$on('ClickEvent',function(event,data){
	$scope.parentMessage=data;
});

});

        

Example of $emit and $on:
 

var app=angular.module('MyApp',[]);

app.controller('ParentCtrl',function($scope){
$scope.$on('ClickEvent',function(event,data){
	$scope.childMessage=data;
});

});

app.controller('childCtrl',function($scope){

$scope.$emit('ClickEvent',"Hello Angular");

});
        

About Author

Author Image
Pulkit Chadha

Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.

Request for Proposal

Name is required

Comment is required

Sending message..