Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simplified AngularJS Dependency Injection logic
function logProvider(){
return function (){
console.log.apply(console, arguments);
}
}
function scopeProvider($dbAdapter){
this.someVariable = $dbAdapter.getText();
//this.someVariable = 'Some text';
}
function dbAdapterProvider(){
this.getText = function(){
return 'Some text'
}
}
function DemoController($scope, $log) {
$log($scope.someVariable);
}
function parseArguments(fnText){
return fnText.slice(fnText.indexOf('(') + 1, fnText.indexOf(')')).match(/([^\s,]+)/g);
}
function getProviderMethod(provider){
return window[provider.replace('$', '') + 'Provider']
}
function getInjectors(fn){
if(!fn.length){
//no injectors
return [];
}
var args = parseArguments(fn.toString()) || [],
injectors = [];
args.forEach(function(arg){
var provider = getProviderMethod(arg);
injectors.push(ObjectFactory(provider, getInjectors(provider)));
})
return injectors;
}
function invoke(fn){
fn.apply(window, getInjectors(fn));
}
invoke(window['DemoController']);
function ObjectFactory(Constructor, args) {
var Temp = function(){},
inst, ret;
Temp.prototype = Constructor.prototype;
inst = new Temp;
ret = Constructor.apply(inst, args);
return Object(ret) === ret ? ret : inst;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.