Reputation: 9474
I am learning AngularJS, and am currently trying master Dependency Injection.
When I define a controller, the documentation tells me that specifying dependencies through annotations, and just listing them in the parameter list for the constructor are equivalent. Hence, I should get the same outcome if I write either:
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', ['$scope', '$location', function ($scope, $location) {
// ... some code
}]);
or:
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', function ($scope, $location) {
// ... some code
});
Is there any practical reasons I should prefer the former, since it seems to be needlessly verbose?
Upvotes: 1
Views: 81
Reputation: 872
The former is used for JavaScript minification, which changes parameter names and thus would break the name-based DI. String values "survive" the minification and let Angular "know" which parameter should be bound to which dependency.
You can use the latter and use https://github.com/btford/ngmin to generate the strings array in build time.
Upvotes: 0
Reputation: 14440
This syntax is needed when you want to keep your dependency injected when minifying your code (var name will be replaced, so dependencies will be affected) :
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', function (a, b) {
// ... some code
});
a, b dependencies doesn't exists ... so code will crash
angular
.module('myapp.controllers', [])
.controller('MainNavigationController', ['$scope', '$location', function (a, b) {
// ... some code
}]);
a, b are being tied to real dependency string.. OK after minification
See : https://docs.angularjs.org/guide/di
Upvotes: 1