4

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 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.