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 Yure Pereira

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.run(function($rootScope) {
    /*
        Receive emitted message and broadcast it.
        Event names must be distinct or browser will blow up!
    */
    $rootScope.$on('handleEmit', function(event, args) {
        $rootScope.$broadcast('handleBroadcast', args);
    });
});

function ControllerZero($scope) {
    $scope.handleClick = function(msg) {
        $scope.$emit('handleEmit', {message: msg});
    };
}

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

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

ControllerZero.$inject = ['$scope'];

ControllerOne.$inject = ['$scope'];

ControllerTwo.$inject = ['$scope'];