So I have a service which I want to allow to listen to events that are fired elsewhere.
I found this question which gives a partial solution: How do i use $on in a service in angular?
However what I've got are a single Listen
service which handles listeners for all my code.
Now I would like to listen to one of the listeners on the Listen
service from my user
service.
What I've got so far is this:
angular.module('app')
.factory('Listen', function ($rootScope) {
var service = {
...
a bunch of event listeners
...
// Event listener
unique: function(scope, name, callback) {
var handler = $rootScope.$on('unique-' + name, callback);
scope.$on('$destroy', handler);
},
activateUnique: function(name){
$rootScope.$emit('unique-' + name);
}
};
return service;
});
angular.module('app')
.factory('userService', function (Listen) {
console.warn('LOADING: user.service.js');
var session,
id,
callDone = false,
service = {
...
some service functions
...
};
service.startSession();
Listen.unique($scope, id, function() {
callDone = true;
});
return service;
});
As you might noticed the Listen.unique
function needs a $scope
, which is fine when listening from a controller
but not when listening from a service, is there a way to get aroung this without making a new $rootScope.$on('unique-' + name, callback);
in userService
?