user2802557 user2802557 - 5 months ago 9
AngularJS Question

Why can't you change argument names in Angular

In angular, here is the simple example for using $http.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});


What I don't understand is that $http is the name of the argument in the callback function so why does it make a difference if you rename it to something else?

For example in JavaScript these two are obviously the exact same function

function(a, b) {
return a+b;
}

function(c, d) {
return c+d;
}


But in this case if I replace $http with anything else such as $HTTP it will break?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $HTTP) {
$HTTP.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});

Answer

You certainly can use other names, and in specific cases you should! Here's how:

angular.module('myApp', [])
  .controller('myCtrl', ["$scope", "$http", function(thescope, thebackend) {
    thebackend.get("welcome.htm")
      .then(function(response) {
        thescope.myWelcome = response.data;
      });
  }]);

Here the second argument for controller(...) is an array, with a specific structure.

  • In order a list of strings with the names of services you want angular to inject;
  • Finally, the last item is your controller constructor function, that takes arguments to be filled with services you asked for earlier in the array.

With this structure you can name the arguments anything you like.

The advantage: you can now minify this code. Minification will leave the strings in the array alone, thus leaving the correct service names for Angular to recognize. The arguments will be safely minified as they can be anything anyways.

The version you had, without such an array, will use the names of arguments to find the appropriate services. If you'd name those arguments differently, Angular would not be able to know what service to inject into that argument.

For quick demo's and adhoc applications your version works fine. This is why you often see it, especially in docs or in SO answers and questions. For production apps I recommend always using the minification-safe version.

The other answer by @slugonamission also has some good nuggets of info, including a link to the appropriate documentation article on Dependency Injection.

PS. Yes, your second example will break, which you can easily try. There's no way for angular to know what $HTTP is, because it only knows about $http.