Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How does the DI system know of the name of the arguments?

Tags:

Example straight from the official site:

function PhoneListCtrl ($scope, $http) {     $http.get('phones/phones.json').success(function(data) {         $scope.phones = data;     });      $scope.orderProp = 'age'; } 

The $scope and $http arguments are unique identifiers for locating corresponding AngularJS services inside the DI system. So how does the DI system retrieve the variable name of these arguments, exactly?

like image 879
gsklee Avatar asked Mar 07 '13 11:03

gsklee


1 Answers

This is the trimmed down version of the way

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     if (!($inject = fn.$inject)) {         $inject = [];         fnText = fn.toString().replace(STRIP_COMMENTS, '');         argDecl = fnText.match(FN_ARGS);         angular.forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){             arg.replace(FN_ARG, function(all, underscore, name){                 $inject.push(name);             });         });         fn.$inject = $inject;     }      return fn.$inject; } 

Demo: Fiddle(See the console);

Steps:
1. Calling toString in the function returns the function source
2. Remove all comments using regex
3. Extract the arguments from the source using regex

like image 90
Arun P Johny Avatar answered Oct 18 '22 16:10

Arun P Johny