AngularJS - Communication Between Controllers & Directive
This is an example of how to use a custom service to facilitate communicate between multiple controllers using $rootscope as an event bus.
I added in a directive just for fun.
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div ng-controller="ControllerZero">
<input ng-model="message" >
<button ng-click="handleClick(message);">BROADCAST 1</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
<button ng-click="handleClick(message);">BROADCAST 2</button>
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
<my-component></my-component>
JavaScript
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
controller: function($scope, $element, $attrs, mySharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'Directive: ' + mySharedService.message;
// $scope.$digest();
});
$scope.handleClick = function(msg) {
mySharedService.prepForBroadcast(msg);
};
},
link: function($scope, $element, $attrs) {
$('.test2').on('click', function(){
alert('clicked on test2');
$scope.handleClick('test2');
});
},
replace: true,
template: '<div><input ng-model="message"> <button ng-click="handleClick(message)">BROADCAST 3</button> <button class="test2">test2</button></div>'
};
});
function ControllerZero($scope, sharedService) {
/*
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
*/
$scope.$on('handleBroadcast', function() {
alert('Ctrl0 has recognized handleBroadcast');
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
/*
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
*/
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
...