AngularJS - Simple $broadcast and $on example
HTML
<div ng-app="myApp">
<div ng-controller='ControllerA'>
<button ng-click='add()'>Add</button>
<div>
<div ng-controller='ControllerB'>
{{ increment }}
<div>
</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('ControllerA', ['Factory', '$scope', '$rootScope', function(Factory, $scope, $rootScope) {
$scope.add = function() {
Factory.send('new Message!'); //it works!
}
Factory.send('new Message!'); //doesnt' work
}]);
app.controller('ControllerB', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.$on('hi', function(event, msg) {
console.log('event fired!');
$scope.increment = msg;
});
}]);
app.factory('Factory', function($rootScope) {
var self = this;
self.send = function(msg) {
console.log('Factory method run');
$rootScope.$broadcast('hi', msg);
}
return self;
});