Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to emit events from a factory

Tags:

angularjs

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

like image 542
murtaza52 Avatar asked Dec 27 '12 15:12

murtaza52


Video Answer


2 Answers

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.

like image 199
Mathew Berg Avatar answered Oct 04 '22 20:10

Mathew Berg


You cannot inject a controller's scope into a service. What you can do is:

  • pass the scope instance as a parameter to one of your service functions:

e.g.

app.factory('MyService', function() {

   return {
      myFunction: function(scope) {
         scope.$emit(...);
         ...
      }
    };
});
  • inject the $rootScope into your service:

e.g.

app.factory('MyService', ['$rootScope', function($rootScope) {

   return {
      myFunction: function() {
         $rootScope.$emit(...);
         ...
      }
    };
}]);
like image 35
asgoth Avatar answered Oct 04 '22 21:10

asgoth