emit and broadcast Angular

by shushanth pallegar

HTML

<body ng-app="App">
    
    
    <div ng-controller="firstCtrl">
        <label>Enter the message to broadcast</label>    
        <input type="text" ng-model="message"/>
        <button ng-click="broadcast(message)">broadcast!!!</button>
        <p>
            <span>BroadCast Message :{{broadcastMsg}}</span>
            <span>emit Message :{{emitMsg}}</span>
        </p>
    </div>
    
    
    <div ng-controller="secondCtrl">
        
        <p>
             <span>BroadCast Message :{{broadcastMsg}}</span>
            <span>emit Message :{{emitMsg}}</span>
        
        </p>
        
    </div>
    
<div ng-controller="thirdCtrl">
        
        <span>BroadCast Message :{{broadcastMsg}}</span>
            <span>emit Message :{{emitMsg}}</span>
        
    </div>
    
<div ng-controller="fourthCtrl">
    
        <p>
           <span>BroadCast Message :{{broadcastMsg}}</span>
            <span>emit Message :{{emitMsg}}</span>
       </p>
    <p>
       <label>Enter the message to emit</label>    
        <input type = "text" ng-model="message"/>
    <button ng-click="emit(message)">Emit !!!</button>
    </p>
        
    </div>    
    
    
</body>

JavaScript

var myApp = angular.module('App',[]);


//first controller 
myApp.controller('firstCtrl',firstCtrl);

//inject dependencies (angular providers)
firstCtrl.$inject = ["$scope","$rootScope"];


function firstCtrl($scope,$rootScope) {
    
    $scope.broadcast = function(bcMsg){
       
       $scope.broadcastMsg = bcMsg;
       $rootScope.$broadcast('broadC',$scope.broadcastMsg);
    }  
    
    $rootScope.$on('emitC',function(events,data){
        $scope.emitMsg = data;
    });
}


//second controller
myApp.controller('secondCtrl',secondCtrl);

//inject dependencies
secondCtrl.$inject = ["$scope","$rootScope"];

function secondCtrl($scope,$rootScope) {
    
    $scope.$on('broadC',function(events,data){
        $scope.broadcastMsg=data;
    });
    
    $rootScope.$on('emitC',function(events,data){
        $scope.emitMsg = data;
    });
        
}


//third controller
myApp.controller('thirdCtrl',thirdCtrl);

//inject dependencies
thirdCtrl.$inject = ["$scope","$rootScope"];

function thirdCtrl($scope,$rootScope) {
    
    $scope.$on('broadC',function(events,data){
        $scope.broadcastMsg=data;
    });
    
    $rootScope.$on('emitC',function(events,data){
        $scope.emitMsg = data;
    });
        
}

//fourth controller
myApp.controller('fourthCtrl',fourthCtrl);

//inject dependencies
fourthCtrl.$inject = ["$scope","$rootScope"];

function fourthCtrl($scope,$rootScope) {
    

    $scope.emit=function(emMsg) {
        $scope.emitMsg = emMsg;
        $scope.$emit('emitC',$scope.emitMsg);
    
    }
    
    $scope.$on('broadC',function(events,data){
        $scope.broadcastMsg=data;
    })
    
    
        
}