AngularJS控制器注入依赖 - 为什么构造函数有[]?

时间:2014-12-18 14:23:40

标签: javascript angularjs

通过AngularJS文档挖掘我发现了以下examples

angular.module('invoice1', [])
.controller('InvoiceController', function() {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = ['USD', 'EUR', 'CNY'];
  this.usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };

  this.total = function total(outCurr) {
    return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
  };
  this.convertCurrency = function convertCurrency(amount, inCurr, outCurr) {
    return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];
  };
  this.pay = function pay() {
    window.alert("Thanks!");
  };
});

这非常精细和清晰。 InvoiceController的构造函数直接在.controller()中作为第二个参数调用。

进一步设置依赖项以注入InvoiceController,给出以下代码:

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!");
  };
}]);

使用finance2.js

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
  };
});

我目前无法理解为什么注入的语法需要第二个参数的[]括号。 我可以看到模块的依赖关系的定义,并且有充分的文档说明它需要输入到[]的{​​{1}} 但为什么需要.module()而不是.controller('name', [constructor(dependency-param]) .controller('name', constructor(dependency-param))

2 个答案:

答案 0 :(得分:2)

这个问题在kokeksibir的链接中得到了很好的描述...... 总结一下:
Angular将控制器的依赖关系从参数名称推断到控制器的构造函数。在缩小过程之后,函数名称被改变;用字符串提供的依赖项名称来注释函数,解决了这个问题。

答案 1 :(得分:1)

请参阅https://docs.angularjs.org/tutorial/step_05部分"关于缩小的注意事项"用于文档。

您在MarcoS'下撰写的评论回答;

  

第二个参数可以是对象,函数构造函数还是数组中具有不同可能的声明可能性的数组,这是正确的吗?

第二个参数可以是函数,也可以是由依赖关系名称组成的数组作为字符串,控制器函数作为最后一个元素。第二个参数不能是对象。第一个参数可以是一次声明一组控制器的对象:

{"nameOfController": function(aDInameThatIsUnsafe){...}, "anotherController": ["firstDI", "secondDI", function(firstDI, secondDI) {...}]}