Use Broadcast, Emit And On in AngularJS
Posted By : Pulkit Chadha | 27-Sep-2017
Introduction:
In
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");
});
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pulkit Chadha
Pulkit is an expert web app developer and has good knowledge of JQuery, MongoDb, NodeJs, AngularJS, kaltura, Akamai. etc.