Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This question already has an answer here:

HI I've seen 2 ways of dependency injection in angularjs controller Method1:

 mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {}); 

Method2:

mainApp.controller('CalcController', ['$scope', 'CalcService', 'defaultInput',function($scope, CalcService, defaultInput) {}]);

What is the diffrence between method1 and method2?

share|improve this question

marked as duplicate by Community Dec 3 '15 at 14:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

The second method makes your injections minification safe. The actual parameter names get shortened but by supplying them double it still can be mapped.

So you should use the second method.

share|improve this answer

Method 1 does not work when you minify the javascript since "CalcService" will be renamed to something like "_a", thats why in version 2, you persist the name since minifiers don't touch strings. Hence the service name is intact.

share|improve this answer

Method two allows your code to be minified and still function correctly.

Javascript does not have named function parameters, however angular's dependency system kindof extends this to allow for named parameters (thats just its dependency system, not as whole). Thats how it knows what to inject.

However minifying your code renames function parameters breaking angulars injection system.

What angular will do is use the array to find the actual dependency by name, then insert it into the variable of that position in the function. This means the order in the array has to match the order of function parameters that you wish to use.

share|improve this answer

Official Angular Docs on Dependency Injection -

https://github.com/angular/angular.js/blob/master/docs/content/guide/di.ngdoc#L103

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.