为什么在创建组件时在AngularJs中使用方括号表示法 [英] Why use square brackets notation in AngularJs when creating components

查看:71
本文介绍了为什么在创建组件时在AngularJs中使用方括号表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们创建控制器,服务等组件时,AngularJs中使用方括号有什么用?我在示例中看到了['ngRoute','ngFileUpload'].它有什么用?

What is the use of square brackets in AngularJs when we are creating components such as controllers, services, etc? I have seen ['ngRoute', 'ngFileUpload'] in examples. What is the use of it?

推荐答案

它是定义角度依赖注入的方式,因此您可以在不破坏源代码的情况下丑化源代码.

Its the way angular dependency injection was defined so you can uglify the source code without breaking it.

例如,控制器可以定义两个依赖关系,如下所示:

For example, a controller may define two dependencies like this:

angular.module('App').controller('SomeController', ['ngRoute', 'ngFileUpload', function (route, fileUpload) {
    console.log('this is ngRoute', route);
    console.log('this is fileUpload', fileUpload);
}]);

angular将实例化控制器,其依赖性与数组中的顺序相同.因此,给参数指定名称并不重要.现在想象一下,您想丑陋的代码使它像这样:

angular will instantiate the controller with the dependencies as the same order in the array. So it does not the matter the name you give to the arguments. Now imagine that you want to uglify the code to make it like this:

angular.module('App').controller('SomeController', ['ngRoute', 'ngFileUpload', function (a, b) {
    console.log('this is ngRoute', a);
    console.log('this is fileUpload', b);
}]);

您仍然会像预期的那样获得依赖关系. 但是,如果您使用这种表示法:

You will still get the dependencies as you are supposed to. However, if you used this notation:

angular.module('App').controller('SomeController', function (ngRoute, ngFileUpload) {});

您不能丑化重命名函数参数的代码.

You couldn't uglify the code renaming the function arguments.

这篇关于为什么在创建组件时在AngularJs中使用方括号表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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