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 gorillawit
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/5.5.3/css/foundation.css">
<p>basically you create a service and inject it into each of the controllers so that each of the controllers
can directly call methods on the shared service or </p>
<br>
<br>
<h2>Controller Zero</h2>
<div ng-controller="ControllerZero">
<input ng-model="message">
<button class="radius small right" ng-click="handleClick(message);">LOG</button>
</div>
<br><br>
<h2>Controller One</h2>
<div ng-controller="ControllerOne">
<input ng-model="message">
</div>
<h2>Controller Two</h2>
<div ng-controller="ControllerTwo">
<input ng-model="message">
</div>
CSS
body {
padding: 20px;
}
p {
font-size: 10px;
}
div {
margin-top: 30px;
};
JavaScript
//
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function ($rootScope) {
// object that will always be returned from this service
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function () {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function ControllerZero($scope, sharedService) {
//handle click from html
$scope.handleClick = function (msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function () {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function () {
$scope.message = 'ONE: ' + sharedService.message;
});
}
//function ControllerTwo($scope, sharedService) {
// $scope.$on('handleBroadcast', function () {
// $scope.message = 'TWO: ' + sharedService.message;
// });
//}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
//ControllerTwo.$inject = ['$scope', 'mySharedService'];