AngularJS - Communication Between Controllers

This is an example of how to use a custom service to facilitate communicate between multiple controllers using $rootscope as an event bus.

by eshepelyuk

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">LOG</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

JavaScript

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
    return {
        broadcast: function(msg) {
            $rootScope.$broadcast('handleBroadcast', msg); 
        }
    };
});

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService. broadcast(msg);
    };
        
    $scope.$on('handleBroadcast', function(event, message) {
        $scope.message = 'ZERO: ' + message;
    });        
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function(event, message) {
        $scope.message = 'ONE: ' + message;
    });        
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function(event, message) {
        $scope.message = 'TWO: ' + message;
    });
}

ControllerZero.$inject = ['$scope', 'mySharedService'];                
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];