Angularjs - 在没有参考的情况下注入工厂

Angularjs - Inject factory without reference

我有以下代码:

main.js

angular.controller('myCtrl', function($scope, $rootScope) {
    $scope.name = "Bob";
}

myservices.js

angular.factory('myService', function($http) {

  var myService = {
    async: function(params) {
      // $http returns a promise, which has a then function, which also returns a promise
      var promise = $http.get("http://myws/user/info/"+params).then(function (response) {
        // The then function here is an opportunity to modify the response
        console.log(response);
        // The return value gets picked up by the then in the controller.
        return response.data;
      });
      // Return the promise to the controller
      return promise;
    }
  };
  return myService;
});

如何在myCtrl中注入myService?考虑到它们在两个单独的文件中。

我们需要按顺序将我们创建的所有脚本添加到 运行 此 angular,请注意顺序:

<script src="angular.js"></script>
<script src="main.js"></script>
<script src="myservices.js"></script>

main.js 应如下所示:

var app = angular.module("MyModule", []);
app.controller('myCtrl', function($scope, $rootScope, myService) { /* implementation */})

services.js 应如下所示:

app.factory('myService', function($http) { /* implementation */});

因此,在我们的 main.js 中,我们正在创建一个模块来附加我们所有的服务、工厂、提供者、值、常量、控制器和指令。它还允许我们将配置和 运行 相位函数放入。

模块通过以下方式实例化:

angular.module("MyModule", []);

我们正在提供其他依赖模块的第二个参数

如果需要,我们可以再次向 angular 请求模块,在使用 javascript 模块的情况下:

var app = angular.module("MyModule");

以下是您需要做的几件事。

  1. 应该属于same/different angular module(如果它是不同的模块那么你已经注入主模块使用它)。
  2. 您需要使用 angular.module('myApp') 将组件绑定到它,以便该服务在该模块中可用。

代码

//app.js
angular.module('myApp', ['myApp.service']); //this should be module definition somewhere

//service.js
angular.module('myApp.service', [])
angular.module('myApp.service').factory('myService', function($http) {
     //service code
});

//controller.js
angular.module('myApp').controller('myCtrl', function($scope, $rootScope, myService) {
    console.log(myService); //service instance here
    $scope.name = "Bob";
}
  1. 确保文件都已实际加载。如何做到这一点取决于您,也许您正在使用 require() 的某种实现,或者您只是将 HTML 中的所有文件列为 <script> 标签。

  2. 明确你想要的模块结构。两者应该是同一个模块的一部分,还是应该是单独的模块?

    • 同一个模块:一个文件需要声明模块,另一个需要扩展:

      angular.module('Foo', [])  // declares new module
          .controller(..)
      
      angular.module('Foo')      // extends existing module
          .factory(..)
      
    • 不同模块:

      angular.module('Foo', [])  // declares new module
          .factory(..)
      
      angular.module('Bar', ['Foo'])  // declares new module
          .controller(..)             // and imports other module
      
  3. 注入控制器:

    .controller('myCtrl', function ($scope, myService) ..
    

你可以在你的控制器中注入服务

喜欢:

main.js:

angular.module('myApp', []).controller('myController', ['$scope', 'myService',
    function ($scope, myService) {

    }
]);

myService.js:

angular.module('myApp').factory('myService', function($http) {
     //service code
});

对于不同的文件但相同的模块然后确保文件在使用前加载。