Created
March 5, 2014 14:30
-
-
Save stevermeister/9368235 to your computer and use it in GitHub Desktop.
simplified AngularJS Dependency Injection logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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