how to emit events from a factory

后端 未结 3 2028
时光取名叫无心
时光取名叫无心 2020-12-14 15:17

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 - Unknow

相关标签:
3条回答
  • 2020-12-14 15:49

    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(...);
             ...
          }
        };
    }]);
    
    0 讨论(0)
  • 2020-12-14 15:59

    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.

    0 讨论(0)
  • 2020-12-14 16:08

    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);
    
    })
    }]);
    
    0 讨论(0)
提交回复
热议问题