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 Diogo Soares
HTML
<div ng-controller="ControllerZero">
<button ng-click="handleClick();">BROADCAST</button>
</div>
<div ng-controller="ControllerOne">
<button ng-click="abrir();">ABRIR</button>
<my-component ng-show="visivel"></my-component>
</div>
CSS
.content{
width: 100px;
height: 100px;
background: blue;
}
JavaScript
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.visivel = false;
sharedService.prepForBroadcast = function(status) {
this.visivel = status;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myModule.directive('myComponent', function(mySharedService) {
return {
restrict: 'E',
controller: function($scope, $attrs, mySharedService) {
$scope.$on('handleBroadcast', function() {
$scope.visivel = mySharedService.visivel;
});
},
replace: true,
template: '<div class="content">'
};
});
myModule.controller('ControllerZero', ControllerZero);
function ControllerZero($scope, sharedService) {
$scope.handleClick = function() {
sharedService.prepForBroadcast(true);
};
}
myModule.controller('ControllerOne', ControllerOne);
function ControllerOne($scope, sharedService) {
$scope.abrir = function() {
sharedService.prepForBroadcast(true);
};
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];