Angular.js对象中的函数参数名称如何连接到其他对象?

GSt*_*Sto 18 angularjs

假设我在Angular.js中创建了一个带有服务和控制器的模块,我可以在控制器内部访问该服务,如下所示:

var myapp = angular.module('my-app', []);

myapp.factory('Service', function() {
  var Service = {};
  Service.example = 'hello';
  //etc..
  return Service;
});

myapp.controller('mainController', function($scope, Service) {
  $scope.greeting= Service.example;
});
Run Code Online (Sandbox Code Playgroud)

在此示例中,Service对象将传递给控制器​​,并且像这样构造代码不会更改代码的行为:

myapp.controller('mainController', function(Service, $scope) {
  $scope.greeting= Service.example;
});
Run Code Online (Sandbox Code Playgroud)

那么,Angular.js如何"知道"函数参数的含义?

Jam*_*ice 21

Angular只是解析toString()函数的表示形式的依赖项名称.来自文档:

在JavaScript中调用toString()函数返回函数定义.然后可以解析定义并提取函数参数.

但请注意,如果您的代码缩小,此方法将失败.出于这个原因,Angular支持使用数组的替代方法(我建议总是使用它)语法:

myapp.controller('mainController', ["$scope", "Service", function($scope, Service) {
  $scope.greeting= Service.example;
}]);
Run Code Online (Sandbox Code Playgroud)

  • 函数上的`toString`,是吗?毛.但它解释了唠叨的命名论证魔法.作为Angular的新手,这似乎是一个过度设计的"解决方案",打破了变量命名的基本规则 - 它的名称无关紧要.我将坚持使用`require`-esque显式定义的依赖数组. (5认同)

Ste*_*wie 6

这是通过非常聪明的方法annotate()实现的,该方法对函数签名源(使用function.toString())进行正则表达式扫描,并迭代地将每个函数参数推送到函数$inject数组中.

手动指定$inject数组时,可以完成相同的结果,如下所示:

var MyController = function($scope, myService) {
  // ...
}
// Define function dependencies
MyController.$inject = ['$scope', 'myCustomService'];
Run Code Online (Sandbox Code Playgroud)