为什么我们在数组和函数中注入参数 [英] Why we inject parameter inside array and function
问题描述
我是 Angular 开发的初学者.我不知道为什么我们要为控制器注入两次参数,例如:
I'm a beginner in Angular development. I don't know why we inject twice argument inside for controller like:
app.controller('mycontroller', ['$scope', 'myFactory', 'Myothers', function ($scope, myFactory, Myothers) {}])
看看
app.controller('mycontroller', function ($scope, myFactory, Myothers) {})
您能解释一下我们为什么要这样做吗?
Could you explain why we do this?
推荐答案
原因是为了保护代码不被 javascript 压缩.
The reason is to protect the code from javascript minification.
$inject
确保变量名以字符串的形式保存.
The $inject
makes sure that the variable names are preserved in the form of strings.
理想情况下,您的应用代码应如下所示:
So ideally your app code should look something like this:
var app = angular.module('YourApp', []);
var appCtrl = app.controller('AppCtrl', AppCtrl);
appCtrl.$inject = ['dep1', 'dep2']; //add all the dependencies
function AppCtrl (dep1,dep2){ //add the name of the dependencies here too
//your controller logic
}
在压缩过程中,javascript 会用自定义名称替换变量名,因此 dep1
可能会被 d
替换,因此会导致错误.
During minification javascript replaces variable name with custom names, so dep1
might be replaced by d
and hence will cause error.
但是 $inject
会让 angular 知道依赖的实际名称是 dep1
因为它以 string
值的形式存储防止缩小.
But $inject
will let angular know that the actual name of the dependency is dep1
as it is stored in the form of string
value which is protected from minification.
因此我们使用 $inject
.
这篇关于为什么我们在数组和函数中注入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!