AngularJS DI注解 - 为什么使用它们? [英] AngularJS DI annotations - why use them?
问题描述
我学习AngularJS,和我目前正在主依赖注入。
I am learning AngularJS, and am currently trying master Dependency Injection.
当我定义了一个控制器,文档告诉我通过注释指定的依赖,以及刚刚上市他们在构造函数的参数列表是等价的。因此,我应该得到相同的结果,如果我写的不是:
When I define a controller, the documentation tells me that specifying dependencies through annotations, and just listing them in the parameter list for the constructor are equivalent. Hence, I should get the same outcome if I write either:
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', ['$scope', '$location', function ($scope, $location) {
// ... some code
}]);
或
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', function ($scope, $location) {
// ... some code
});
有没有实际的原因,我应该preFER前者,因为它似乎是不必要的冗长?
Is there any practical reasons I should prefer the former, since it seems to be needlessly verbose?
推荐答案
当你要保持你的依赖,需要这样的语法与缩小您的code(VAR的名称将被更换,这样的依赖会受到影响),当注射:
This syntax is needed when you want to keep your dependency injected when minifying your code (var name will be replaced, so dependencies will be affected) :
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', function (a, b) {
// ... some code
});
A,B的依赖性不存在......因此code会崩溃
a, b dependencies doesn't exists ... so code will crash
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', ['$scope', '$location', function (a, b) {
// ... some code
}]);
A,B是被捆绑到真正的依赖字符串.. OK缩小后
a, b are being tied to real dependency string.. OK after minification
请参阅: https://docs.angularjs.org/guide/di
这篇关于AngularJS DI注解 - 为什么使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!