1

I have seen people using arrays in parameters like so

myAngularApp.controller("nameOfController", ["$firstDependency", "$secondDependency", function ($firstDependency, $secondDependency) {

// code here
}]);

On the other hands I have seen the following code too, and both are working

myAngularApp.controller("nameOfController", function ($firstDependency, $secondDependency) {

// code here
});

In angular documentation I see the use of arrays. Why is angular allowing the latter method? Which one is absolute recommendation? In fact, in angular documentation samples, the directives don't use arrays.

1
  • the named array is just for min-safing your code. This is generally the best approach you can take Commented Nov 19, 2015 at 16:31

2 Answers 2

2

The $injector has to know what arguments to inject into a function. There are three different ways to tell the injector what to inject.

Option 1: Add an attribute called $inject to the function:

FN.$inject=['$firstDependency','$secondDependency']

Option 2: Use array like annotation:

['$firstDependency','$secondDependency', function(x,y) {...}]

Option 3: If there is no $inject attribute and no annotation, AngularJS uses the function arguments:

function ($firstDependency,$secondDependency) {...}.

The third alternative can't be used if you minify your code, because this will change the argument names.

All three methods are legal and provide the same result.

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

Comments

1

I recommend using the first method:

myAngularApp.controller("nameOfController", ["$firstDependency", "$secondDependency", function ($firstDependency, $secondDependency) {

// code here
}]);

This is because you can minify your code with this method, whereas you cannot with the other method you listed.

1 Comment

This is the correct way to go if you're minifying your source.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.