Angularjs inject provider into module factory function by string name for minification

后端 未结 3 633
离开以前
离开以前 2021-02-18 18:27

I have the following code:

appModule = angular.module(\'appModule\', []);

appModule.factory(\'sharedApplication\', function($rootScope, $http) {
  var sharedApp         


        
相关标签:
3条回答
  • 2021-02-18 18:45

    ng-annotate is also a good library so that the required dependency is injected automatically. You should check it out.

    Code sample:

    /* ngInject */
    appModule.factory('sharedApplication', function($rootScope, $http) {
      var sharedApp;
      sharedApp = {};
      sharedApp.currentView = "home-section";
      sharedApp.pastEvents = null;
      $http.get('api/highlights').success(function(response) {
        return sharedApp.pastEvents = response.data;
      });
      return sharedApp;
    });
    

    Then you don't have to write:

    appModule.factory('sharedApplication', ['$rootScope','$http', 
    function($rootScope, $http) {
     var sharedApp;
     sharedApp = {};
     sharedApp.currentView = "home-section";
     sharedApp.pastEvents = null;
     $http.get('api/highlights').success(function(response) {
     return sharedApp.pastEvents = response.data;
    });
    
    return sharedApp;
    }]);
    
    0 讨论(0)
  • 2021-02-18 18:53

    Try

    appModule.factory('sharedApplication', ['$rootScope','$http',function($rootScope, $http) {
    
    }]);
    

    regards

    0 讨论(0)
  • 2021-02-18 19:09

    The more elegant and easier to read approach:

    appModule.factory('myFactory', myFactory);
    
    myFactory.$inject = ['$rootScope','$http'];
    function myFactory($rootScope, $http) {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题