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.
by flek
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="Ctrl">
<input ng-model="currency" >
<button ng-click="handleClick(currency);">Change currency</button>
</div>
<my-currency currency="{{currency}}"></my-currency>
JavaScript
var myModule = angular.module('myModule', []);
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() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];