Sometimes we need to send data from one controller to another. There are services provided by AngularJS for communication(event-based) between the controllers. $on, $emit, $broadcast are the services for the communication between the controllers.
$on :- $on is used to catch the event dispatched by $broadcast and $emit. Basically it’s a method of scope and listens on events of a given type.
$broadcast : - $broadcast is the service that dispatches an event downwards to the child scopes. The life cycle of the event starts at the scope where the $broadcast is called. For example :-
 
app.controller(Eg1ctrl, function ($scope) {
 $scope.$broadcast('eventName', { Tips: tip });
 });
 
 app.controller("Eg2ctrl", function ($scope) {
 $scope.$on('eventName', function (event, args) {
 $scope. Tips = args. Tips;
 console.log($scope. Tips);
 });
 });
   If scope of Eg1ctrl is parent of the Eg2ctrl scope, it should work by using $broadcast in Eg1ctrl. This event cannot be cancelled.
$emit :- $emit is the service that dispatches an event upwards to the parent scopes. The life cycle of the event starts at the scope where the $emit is called. All the listeners along the way gets notified. For example :-
 app.controller("Eg1ctrl", function ($scope) {
 $scope.$on('eventName', function (event, args) {
 $scope.Tips = args.Tips;
 console.log($scope.Tips);
 });
 });
 
 app.controller("Eg2ctrl", function ($scope) {
  $scope.$emit('eventName', { Tips: tip });
 });
If scope of Eg1ctrl is parent of the Eg2ctrl scope, it should work by using $emit in Eg2ctrl. This event stops moving if one of the listeners cancels it .
 
                       
                    
0 Comment(s)