How can I emit events from a factory or service. I am unable to inject $scope into the factory, thus unable to emit events.
I get the following error - Unknown provider: $scopeProvider <- $scope
Thanks, Murtaza
How can I emit events from a factory or service. I am unable to inject $scope into the factory, thus unable to emit events.
I get the following error - Unknown provider: $scopeProvider <- $scope
Thanks, Murtaza
Inject $rootScope instead of $scope and then emit it on the $rootScope.
myApp.factory('myFactory', ['$rootScope', function ($rootScope) {
$rootScope.$emit("myEvent", myEventParams);
}]);
Factories don't have access to the current controller/directive scope because there isn't one. They do have access to the root of the application though and that's why $rootScope is available.
You cannot inject a controller's scope into a service. What you can do is:
e.g.
app.factory('MyService', function() {
return {
myFunction: function(scope) {
scope.$emit(...);
...
}
};
});
e.g.
app.factory('MyService', ['$rootScope', function($rootScope) {
return {
myFunction: function() {
$rootScope.$emit(...);
...
}
};
}]);
In your factory inject $rootScope as-
myApp.factory('myFactory',function($rootScope){
return({
// use $rootScope as below to pass myEventParams to all below in hierarchy
$rootScope.$broadcast("myEvent",myEventParams);
})
}]);