How does Angular know what to input if I don't specify lines?

Consider this code:

angular.module('app', [])
  .controller('MainCtrl', function ($scope) {
    ...
  });

      

I know that to avoid injection problems when JS is minified, one should use the array form of dependency injection:

angular.module('app', [])
  .controller('MainCtrl', ['$scope', function ($scope) {
    ...
  }]);

      

But how does Angular know in the first case (non-array) what to input? What if I use .controller('MainCtrl', function (scop)

instead $scope

? Is it parsing my JS and looking for function parameter names that match some of its providers?

+3


source to share


1 answer


Note that a function controller

is a parameter to a function controller

. This allows Angular to get this function in a variable and parse its parameters, while Angular makes a list of services to be injected.

In the code below, you can see what Angular is doing behind the scenes to match these parameters:



var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;

function annotate (fn) {
  var $inject = [];
  fn = fn.toString();
  var first = fn.replace(STRIP_COMMENTS, '');
  var second = first.match(FN_ARGS)[1];
  var third = second.split(FN_ARG_SPLIT);
  third.forEach(function (arg) {
    arg.replace(FN_ARG, function (all, underscore, name) {
      $inject.push(name);
    });
  });
  return $inject;
}

      

+4


source







All Articles