为什么我们在数组和函数中注入参数 [英] Why we inject parameter inside array and function

查看:47
本文介绍了为什么我们在数组和函数中注入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆