feat(injector): support ['$service', function($service){}] annotations for function invocation.

This commit is contained in:
Misko Hevery 2011-10-26 20:54:45 -07:00
parent d12df0d360
commit 411c1ae77e
2 changed files with 49 additions and 13 deletions

View file

@ -59,8 +59,17 @@ function createInjector(factories) {
function invoke(self, fn, args, path){
args = args || [];
var injectNames = fn.$inject || [];
var i = injectNames.length;
var injectNames;
var i;
if (typeof fn == 'function') {
injectNames = fn.$inject || [];
i = injectNames.length;
} else if (fn instanceof Array) {
injectNames = fn;
i = injectNames.length;
fn = injectNames[--i];
}
assertArgFn(fn, 'fn');
while(i--) {
args.unshift(injector(injectNames[i], path));
}

View file

@ -18,17 +18,6 @@ describe('injector', function() {
expect(injector('instance')).toEqual(original);
});
it("should call function", function() {
providers('a', function() {return 1;});
providers('b', function() {return 2;});
var args;
function fn(a, b, c, d) {
args = [this, a, b, c, d];
}
fn.$inject = ['a', 'b'];
injector.invoke({name:"this"}, fn, [3, 4]);
expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);
});
it('should inject providers', function() {
providers('a', function() {return 'Mi';});
@ -82,6 +71,44 @@ describe('injector', function() {
expect(injector('eager')).toBe('foo');
});
describe('invoke', function(){
var args;
beforeEach(function(){
args = null;
providers('a', function() {return 1;});
providers('b', function() {return 2;});
});
function fn(a, b, c, d) {
args = [this, a, b, c, d];
}
it('should call function', function() {
fn.$inject = ['a', 'b'];
injector.invoke({name:"this"}, fn, [3, 4]);
expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);
});
it('should treat array as annotations', function(){
injector.invoke({name:"this"}, ['a', 'b', fn], [3, 4]);
expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]);
});
it('should fail with errors if not function or array', function(){
expect(function(){
injector.invoke({}, {});
}).toThrow("Argument 'fn' is not a function, got Object");
expect(function(){
injector.invoke({}, ['a', 123]);
}).toThrow("Argument 'fn' is not a function, got number");
});
});
describe('annotation', function() {
it('should return $inject', function() {
function fn() {}