While reading through documentation on AngularJS services, I've stumbled across example services written like:
myApp.service('fooGetter', ['$http', function($http) {
this.getFoo = function() {
// use $http to get some foo
}
}]);
where $http
is injected to the service wrapper so it can be referenced from within the service instance that is created. What is the reason for array syntax that contains the list of parameters, which are then duplicated in the function parameters? I haven't been able to find a good explanation of the purpose of that, it's rules, and why it's necessary. The same service, written without that, like:
myApp.service('fooGetter', function($http) {
this.getFoo = function() {
// use $http to get some foo
}
});
seems to have a perfectly fine automagic reference to that variable.
If you use the syntax without the array containing the injected dependencies, angular uses reflection to read the arguments to your function. This works fine normally, but if you want to minify your code, your arguments will change name, and angular will stop working. Using the array syntax notation will allow angular to continue to find the correct dependencies even if your argument names change.
Additionally, if your injected services have really long names, you can inject them using the array syntax and give them an easier name to use in the function arguments list.
Example:
app.controller("MyCtrl", ["MyReallyLongUserServiceName", function(User) {
User.doSomething();
}]);