AngularJS: $rootScope.$broadcast vs $rootScope.$emit

Shows how $rootScope.$broadcast and $rootScope.$emit work

HTML

<div ng-app="testapp">
  <h4>
    RootScope Emit and Broadcast test
  </h4>

  <div ng-controller="FirstController">
   
    <button  ng-click="rootScopeEmit()">
      $rootScope.$emit()
    </button>
    <br/>
    $rootScope.$on subscriber:
    <span>{{ testValue }}</span>

  </div>
  
  <div ng-controller="SecondController">
        $scope.$on subscriber:
        <span>{{ testValue }}</span>
     </div>
  
  <div ng-controller="ThirdController">
        $rootScope.$on subscriber:
        <span>{{ testValue }}</span>
     </div>
  
    
   
   
  
</div>

JavaScript

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

//FIRST CONTROLLER
app.controller('FirstController', ['$scope','$rootScope', function ($scope, $rootScope) {
   
   $scope.testValue = "";
  
   $scope.rootScopeEmit = function(){
   
   		 //Notify $rootScope.$on listeners only
   		 $rootScope.$emit('testEvent', "Emit data");
   }
   $rootScope.$on('testEvent', function(event, data){
       $scope.testValue = data;
   });
   
}]);

app.controller('SecondController', ['$scope', function ($scope) {
   $scope.testValue = "";
   $scope.$on('testEvent', function(event, data){
       $scope.testValue = data;
   });
}]);

app.controller('ThirdController', ['$scope', '$rootScope', function ($scope, $rootScope) {
   $scope.testValue = "";
   $rootScope.$on('testEvent', function(event, data){
       $scope.testValue = data;
   });
}]);