Conditional injection of a service in AngularJS

前端 未结 3 1917
独厮守ぢ
独厮守ぢ 2020-12-11 19:53

I have defined a service like this :

angular.module(\'myApp\').service(\'myService\', [
\'$rootScope\',
...
...

I want my service to be in

3条回答
  •  悲&欢浪女
    2020-12-11 20:48

    You can use the $injector service to get inject-ibles dynamically if you need to:

    app.controller('DemoCtrl', function($injector) {
      this.clicky = function() {
        myFact = $injector.get('myFactory');
        myFact();
      };
    });
    
    app.factory('myFactory', function() {
      return function() {
        alert('foobar!');
      };
    });
    

    Here's a full running demo: http://jsbin.com/bemakemaja/1/edit

    And the $injector docs: https://docs.angularjs.org/api/auto/service/$injector

    As a general guideline though I'd recommend not designing your services such that simply injecting them has side effects.

提交回复
热议问题