Why use square brackets notation in AngularJs when

2020-07-18 07:16发布

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?

4条回答
Summer. ? 凉城
2楼-- · 2020-07-18 07:19

It is used for annotation. If you use any minification or obfuscation software, your injections will be renamed. The annotations in the array will allow angular to map to the correct methods.

There is more info available in the angular doc on $injector: https://docs.angularjs.org/api/auto/service/$injector

查看更多
Lonely孤独者°
3楼-- · 2020-07-18 07:24

It has no special "AngularJS" significance. It represents a Javascript Array and by doing ['ngRoute', 'ngFileUpload'], you are passing an array of elements (or strings in this case) which are being passed to the function you are calling.

angular.module('myapp', ['ngRoute', 'ngFileUpload']);

Now it is up to the module function to decide how it interprets the array you pass. But to answer your question, it is just an Array.

查看更多
Bombasti
4楼-- · 2020-07-18 07:42

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 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.

查看更多
贼婆χ
5楼-- · 2020-07-18 07:42

The [] parameter in the module definition can be used to define dependent modules.

example,

The empty array in angular.module('myApp', []). This array is the list of modules myApp depends on.

查看更多
登录 后发表回答