0

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?

0

4 Answers 4

1

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.

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

Comments

0

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.

Comments

0

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.

Comments

0

Official Angular Docs on Dependency Injection -

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.