$emit, $broadcast and $on in AngularJS

by mohitagrawalmca

HTML

<fieldset>
  <legend>AngulerJS <b>$emit</b> with $on method Example</legend>
  <div ng-controller="EmitfirstCtrl" style="border:2px solid #E75D5C; padding:2px;">
    <p>Parent Controller Emit Message :{{message}} </p>
    <div ng-controller="EmitsecondCtrl" style="border:2px solid #428bca;">
      Child Controller :
      <input ng-model="msg" />
      <button ng-click="handleClick(msg);">Emit</button>
    </div>
  </div>
</fieldset>
<br/>
<br/>
<fieldset>
  <legend>AngulerJS <b> $Broadcast</b> with $on method Example 1</legend>
  <div ng-controller="BroadcastFirstCtrl" style="border:2px solid #E75D5C; padding:5px;">
    Parent Controller
    <input ng-model="msg">
    <button ng-click="handleClick(msg);">Broadcast</button>
    <br />
    <br />
    <div ng-controller="BroadcastSecondCtrl" style="border:2px solid #428bca;padding:5px;">
      Child Controller Broadcast Message : {{message}}
    </div>
  </div>
</fieldset>
<br/>
<br/>
<fieldset>
  <legend>AngulerJS <b> $Broadcast</b> with $on method Example 2</legend>
  <div ng-controller="BroadcastFirstCtrlEx2" style="border:2px solid #E75D5C; padding:5px;">
    Parent Controller
    <input ng-model="msg">
    <button ng-click="handleClick(msg);">Broadcast</button>
  </div>
  <br />
  <div ng-controller="BroadcastSecondCtrlEx2" style="border:2px solid #428bca;padding:5px;">
    Child Controller Broadcast Message: {{Information}}
  </div>
  <br />
  <div ng-controller="BroadcastThirdCtrlEx2" style="border:2px solid #428bca;padding:5px;">
    Child Controller Broadcast Message: {{Information}}
  </div>
</fieldset>

JavaScript

var MyApp = angular.module('myApp', []);
MyApp.controller("EmitfirstCtrl", function($scope) {

  $scope.$on('eventName', function(event, args) {
    $scope.message = args.message;
  });
});
MyApp.controller("EmitsecondCtrl", function($scope) {
  $scope.handleClick = function(msg) {
    $scope.$emit('eventName', {
      message: msg
    });
  };
});
MyApp.controller("BroadcastFirstCtrl", function($scope) {
  $scope.handleClick = function(msg) {
    $scope.$broadcast('eventName', {
      message: msg
    });
  };
});
MyApp.controller("BroadcastSecondCtrl", function($scope) {
  $scope.$on('eventName', function(event, args) {
    $scope.message = args.message;
    console.log($scope.message);
  });
});
MyApp.controller("BroadcastFirstCtrlEx2", function($scope, $rootScope) {
  $scope.handleClick = function(msg) {
    $rootScope.$broadcast('eventName', {
      Information: msg
    });
  };
});
MyApp.controller("BroadcastSecondCtrlEx2", function($scope) {
  $scope.$on('eventName', function(event, args) {
    $scope.Information = args.Information;

  });
});
MyApp.controller("BroadcastThirdCtrlEx2", function($scope) {
  $scope.$on('eventName', function(event, args) {
    $scope.Information = args.Information;

  });
});