简体   繁体   English

如何从工厂发出事件

[英]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. 我无法将$ scope注入工厂,因此无法发出事件。

I get the following error - Unknown provider: $scopeProvider <- $scope 我收到以下错误 - Unknown provider: $scopeProvider <- $scope

Thanks, Murtaza 谢谢,穆尔塔扎

Inject $rootScope instead of $scope and then emit it on the $rootScope. 注入$ rootScope而不是$ scope,然后在$ 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. 他们确实可以访问应用程序的根目录,这就是$ rootScope可用的原因。

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: 将$ rootScope注入您的服务:

eg 例如

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

   return {
      myFunction: function() {
         $rootScope.$emit(...);
         ...
      }
    };
}]);

In your factory inject $rootScope as- 在你的工厂注入$ rootScope作为 -

myApp.factory('myFactory',function($rootScope){
return({
// use $rootScope as below to pass myEventParams to all below in hierarchy
$rootScope.$broadcast("myEvent",myEventParams);

})
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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