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 gavinfoley

HTML

<script src="https://code.angularjs.org/1.2.19/angular.min.js"></script>
<div ng-controller="ControllerZero">
    <input ng-model="message">
    <button ng-click="cool = !cool; handleClick(cool);">LOG</button>
 
    <div ng-controller="ControllerOne">
        <input ng-model="message2" >
  
    </div>    
</div>

JavaScript

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

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

function ControllerOne($scope) {
    $scope.$on('handleChild', function(event, args) {
        $scope.message2 = 'ONE: ' + args.message;    
        console.log(event);
        // mark event as "not handle in children scopes"
        event.preventDefault();
        
        console.log(event);
    });            
}

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

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