Angular and controller function parameters

I have been doing some work with angular lately and I noticed that it is possible to specify an array of names for dependencies in controller functions. If you do this, the controller still works properly and the dependencies will inject just fine.

I'm sure I am missing something. What is the reason for these names?

+3


source to share


2 answers


See the "Note on Minimization" paragraph at https://docs.angularjs.org/tutorial/step_05

It is used to keep a string reference to your dependency injection after minification:



Since Angular defines controller dependencies on the names of the controller constructor function arguments, if you were to minify the JavaScript code for the PhoneListCtrl controller, all of its function arguments would also be minified, and the dependency injector would not be able to correctly identify the services.

+5


source


Controllers are callers and their arguments must be injected with existing / valid / registered dependencies. Angular has three ways:

  • If the passed controller (this also applies to providers) is an array, the last element is the controller, and the first elements must be dependency-named strings to input. The number of names and arity must match.

    //parameter names are what I want.
    c = mymodule.controller('MyController', ['$scope', '$http', function($s, $h) {}]);
    
          

  • Otherwise, if the passed controller has a property $inject

    , that property is expected to be an array of strings that are dependency names. Array length and arity must match.

    con = function($s, $h) {};
    con.$inject = ['$scope', '$http'];
    c = mymodule.controller('MyController', conn);
    
          

  • Otherwise, the array of injectable names 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 a controller to work unless you explicitly set the -explicitly - dependency names to be inserted. This is bad because:



  • Parameter names will change if you minify (and you will - today - minify your script).
  • A typo in your parameter name, and you'll spend hours looking for an error.

Suggestion: Always use explicit notation (path 1 or 2).

+1


source







All Articles