假设我在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)
这是通过非常聪明的方法annotate(源)实现的,该方法对函数签名源(使用function.toString())进行正则表达式扫描,并迭代地将每个函数参数推送到函数$inject数组中.
手动指定$inject数组时,可以完成相同的结果,如下所示:
var MyController = function($scope, myService) {
// ...
}
// Define function dependencies
MyController.$inject = ['$scope', 'myCustomService'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4565 次 |
| 最近记录: |