How to call a service in another module using $ on and $ broadcast
I am trying to make a call from factory A to factory B using angular $ broadcast. These two factories are defined in separate modules. Below is the code that tries to do this.
angular.module('secondApp', [])
.service('B', function($rootScope, $scope) {
$rootScope.$on('test', function(event, data) {
console.log(event, data);
});
});
var app = angular.module('firstApp', ['secondApp']);
app.controller('MainCtrl', function($scope, A) {
$scope.test = function() {
A.test();
};
});
app.service('A', function($rootScope) {
this.test = function() {
$rootScope.$broadcast('test', 'Hello from service A!');
};
});
source to share
You should use $rootScope.$emit()
instead $rootScope.$broadcast()
.
Because it $rootScope.$broadcast()
will go down.
Edit:
Made a sample code for validating emit / broadcast / on base in Angular: Plunker manual .
It turns out that when used $rootScope.$on
to listen, events will fire $rootScope.$emit
and $rootScope.$broadcast
. The difference $broadcast
will be sent down, so all areas will receive the event as well.
So, if you just want to notify $rootScope
, just use $rootScope.$emit
. $rootScope.$broadcast
will waste resources.
Hope this helps.
source to share