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(...);
...
}
};
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With