为什么我们在数组和函数中注入参数

skv*_*kvj 3 javascript dependency-injection angularjs

我是Angular开发的初学者.我不知道为什么我们为控制器内部注入两次参数:

app.controller('mycontroller', ['$scope', 'myFactory', 'Myothers', function ($scope, myFactory, Myothers) {}])
Run Code Online (Sandbox Code Playgroud)

并看到

app.controller('mycontroller', function ($scope, myFactory, Myothers) {})
Run Code Online (Sandbox Code Playgroud)

你能解释一下我们为什么这样做吗?

Pri*_*jee 6

原因是保护代码免受javascript缩小.

$inject可确保变量名可以字符串的形式保存下来.

理想情况下,您的应用代码应如下所示:

 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
 }
Run Code Online (Sandbox Code Playgroud)

在缩小期间,javascript用自定义名称替换变量名称,因此dep1可能会替换为d,因此会导致错误.

但是$inject让角度知道依赖关系的实际名称dep1是以string值的形式存储,因为它可以防止缩小.

因此我们使用$inject.