简体   繁体   中英

how to emit events from a factory

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:

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

eg

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

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

eg

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);

})
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM