AngularJS - $emit & $on - 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
<div data-ng-app="myApp">
<div ng-controller="ControllerOne">
<input ng-model="message">
<button ng-click="sendmsg(message);">Send from controller 1</button> <br>
Received message: <input ng-model="receivedMessage">
</div>
<br><br><br><br>
<div ng-controller="ControllerTwo">
<input ng-model="message">
<button ng-click="sendmsg(message);">Send from controller 2</button><br>
Received message: <input ng-model="receivedMessage">
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> <link rel="stylesheet" href="//rawgit.com/minipai/ng-trans.css/master/ng-trans.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script> <style>
JavaScript
angular.module('myApp', ['ngAnimate'])
.factory('msgBus', ['$rootScope', function ($rootScope) {
var msgBus = {};
msgBus.emitMsg = function (msg, data) {
data = data || {}
$rootScope.$emit(msg, data);
};
msgBus.onMsg = function (msg, func, scope) {
var unbind = $rootScope.$on(msg, func);
if (scope) {
scope.$on('$destroy', unbind);
}
};
return msgBus;
}])
.controller("ControllerOne", function ($scope, $timeout, msgBus) {
$scope.sendmsg = function (message) {
msgBus.emitMsg('sendMsg.Ctrl1', message);
}
msgBus.onMsg('sendMsg.Ctrl2', function (event, data) {
console.log(data);
$scope.receivedMessage = data;
});
})
.controller("ControllerTwo", function ($scope, $timeout, msgBus) {
$scope.sendmsg = function (message) {
msgBus.emitMsg('sendMsg.Ctrl2', message);
}
msgBus.onMsg('sendMsg.Ctrl1', function (event, data) {
console.log(data);
$scope.receivedMessage = data;
});
});