0

AngularJS supports two slightly different syntaxes for dependency injection

Syntax 1

myModule.controller('myCtrl', function($scope, $http, myService) {
    ...
    ...
});

Syntax 2

myModule.controller('myCtrl', ['$scope', '$http', 'myService', function($scope, $http, myService) {
    ...
    ...
}]);


Is there a fundamental difference between the two syntaxes?
When to use either of the two syntaxes?

4
  • this has been asked many times and is explained in the documentation Commented Oct 8, 2015 at 18:25
  • Take a look at this answer. Commented Oct 8, 2015 at 18:25
  • DI Docs docs.angularjs.org/guide/di Commented Oct 8, 2015 at 18:28
  • Syntax 2 is used for minification. Strings are not modified by minifiers so they are used for mapping the corresponding minified function parameters (injections) so they point back to the correct services. Commented Oct 8, 2015 at 18:29

1 Answer 1

1

Syntax 2 is called type hinting, if you plan to uglify and mangle your code, angular would still know what services to inject.

After mangling and ugilying:

myModule.controller('myCtrl', ['$scope', '$http', 'myService', function(a, b, c) {

Angular would read the string values of the array provided in order to determine the name of the services a, b, c in order to inject them properly.

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

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.