【问题标题】:How to inject a service/factory to be used by a controller?如何注入控制器使用的服务/工厂?
【发布时间】:2014-09-19 13:16:29
【问题描述】:

我是 AngularJS 的新手,我已经花了几个小时在网上搜索这个,但我找不到答案(每个博客或网站似乎都在说不同的东西或者已经过时了)。

我了解服务/工厂可以保存对象及其各自的成员函数。 我想创建这样一个对象的实例,并在 controller.js 文件中使用它们的成员函数(该文件包含应用程序要使用的控制器)。

但是,我根本不明白如何设置服务或工厂以及如何注入它,以便控制器文件可以创建和使用服务中的对象实例。

有人知道任何简单的例子来说明这一点吗?

非常感谢!

【问题讨论】:

标签: angularjs service dependency-injection controller


【解决方案1】:
var myapp = angular.module('myApp',[]);

myapp.service('MyService',['$http', function($http) {
   return {
       doSomeThing: function() {
           // do something here with $http or whatever
       },
       doSomeThingElse: function() {
       }
}
]);

myapp.controller('MyController',['MyService',function(MyService) {


   MyService.doSomeThing();

}]);

【讨论】:

  • 谢谢!但是,如果 myApp、服务和控制器位于不同的文件中,这会是什么样子?这是我真正陷入困境的地方。
  • 看起来几乎一样。在您的服务顶部,只需使用带有单个参数的 myapp=angular.module('myApp') 即可检索先前定义的 myapp。只需在页面中包含两个 .js 文件
【解决方案2】:

经过数小时的搜索,我偶然发现了一个完美的例子,说明如何以干净简单的方式将服务注入控制器。有趣的是,这个例子实际上是在 AngularJS 官方文档的 AngularJS 部分的概述中找到的——说说倒霉吧。

不管怎样,这里是:

HTML

<!--include the separate controller, service, & app js files here -->
<div ng-app="invoice2" ng-controller="InvoiceController as invoice">
<b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required >
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required >
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>
  <div>
    <b>Total:</b>
    <span ng-repeat="c in invoice.currencies">
      {{invoice.total(c) | currency:c}}
    </span>
    <button class="btn" ng-click="invoice.pay()">Pay</button>
  </div>

控制器

angular.module('invoice2', ['finance2'])
.controller('InvoiceController', ['currencyConverter', function(currencyConverter) {
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = currencyConverter.currencies;

this.total = function total(outCurr) {
  return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
};
this.pay = function pay() {
  window.alert("Thanks!");
};
}]);

服务

angular.module('finance2', [])
.factory('currencyConverter', function() {
var currencies = ['USD', 'EUR', 'CNY'];
var usdToForeignRates = {
  USD: 1,
  EUR: 0.74,
  CNY: 6.09
};
var convert = function (amount, inCurr, outCurr) {
  return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
};

return {
  currencies: currencies,
  convert: convert
};
});

希望这个简单的例子可以帮助那些同样难以学习 AngularJS 的人!

示例来自:https://docs.angularjs.org/guide/concepts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    相关资源
    最近更新 更多