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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With