Reputation: 8762
I've been doing some work with angular lately, and I noticed that one can omit the array of names for the dependencies in controller functions. If you do this, the controller still works correctly and dependencies get injected just fine.
I'm sure I'm missing something. What is the reason for those names?
Upvotes: 3
Views: 160
Reputation: 12333
Controllers are callables, and their arguments must be injected with existing/valid/registered dependencies. Angular takes three ways:
If the passed controller (this also applies to providers) is an array, the last item is the controller, and the former items are expected to be strings with the names of dependencies to inject. The names count and the arity must match.
//parameter names are what I want.
c = mymodule.controller('MyController', ['$scope', '$http', function($s, $h) {}]);
Otherwise, if the passed controller has an $inject
property, it is expected that such property is an array of strings being the names of the dependencies. The length of the array and the arity must match.
con = function($s, $h) {};
con.$inject = ['$scope', '$http'];
c = mymodule.controller('MyController', conn);
Otherwise, the array of names to inject is taken from the parameter list, so they must be named accordingly.
c = mymodule.controller('MyController', function($scope, $http) {});
//one type, one minification, and you're screwed
You should never expect that the controller works if you don't explicitly set -explicitly- the names of the dependencies to inject. It is a bad practice because:
Suggestion: always use an explicit notation (way 1 or 2).
Upvotes: 1
Reputation: 14440
See paragraph a "Note on Minification" in https://docs.angularjs.org/tutorial/step_05
It is used to keep a string reference of your injections of dependencies after minifications :
Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.
Upvotes: 5