johny long
johny long

Reputation: 67

Different way of dependency injection in Angular

what's the difference of defining controller's dependencies in array:

app.controller('IndexController', ['$rootScope', '$http', function($rootScope, $http) {
    //some cool stuff
}]);

and injecting them right into the function like this:

app.controller('IndexController', function($rootScope, $http) {
    //some cool stuff
});

Lot of posts and tutorials use the shorter version, so I'm wondering if there's any advantage of doing it the first way.

Thanks!

Upvotes: 0

Views: 29

Answers (1)

Michael
Michael

Reputation: 3326

This is necessary if you use some minification tools such as uglify. These kind of tools change the name of the variables, thus, for example:

app.controller('IndexController', function($rootScope, $http) {
    //some cool stuff
});

Becomes something like:

randomVariable.controller('IndexController',function(a, b){});

And a and b are not your dependencies.

In the other case, the minified code becomes something like:

app.controller('IndexController',['$rootScope','$http',function(a,b)

Here a and b are passed as arguments from two strings that are values and hence they cannot be modified by the minification tools

Upvotes: 2

Related Questions