在Angular中使用$ inject

时间:2017-02-03 17:43:58

标签: angularjs

我有以下代码为其他人写的服务:

'use strict';

    angular.module('maintenance.portability.module')
        .factory('selectedSamplesSvc', service);

    service.$inject = ['$resource'];

function service() {
}
})();

我只想做以下事情:

  1. 注入'$ resource'
  2. 在我的服务中使用$ resource的实例
  3. 我该怎么做?

1 个答案:

答案 0 :(得分:1)

  

您可以通过3种方式注入服务:

  1. 将依赖项作为函数参数传递

     app.controller("TestController", function ($scope) {
      $scope.message = "Hey I am passed as function argument" 
     });
    
  2. 将依赖项作为数组参数传递

     app.controller("TestController", ['$scope', function ($scope) {
      $scope.message = "Hey I am passed in as array argument" 
     }]);
    

    在我们缩小应用程序时,将依赖关系作为数组参数传递不会破坏应用程序。

  3. 使用$ inject服务传递依赖关系

     function TestController($scope){
       $scope.greet = "I am injected using inject service";
     }
    
     TestController.$inject = ['$scope'];
     app.controller('TestController', TestController);
    
  4. 你的第三种方式。对于注入,$ resource服务,在设置角度应用程序时需要 ngResource 模块。

    angular.module('test',['ngResource'])