Skip to content

Instantly share code, notes, and snippets.

@syul
Created July 26, 2016 11:59
Show Gist options
  • Save syul/60f59c6ecc47f2621ee810cc3c0deadf to your computer and use it in GitHub Desktop.
Save syul/60f59c6ecc47f2621ee810cc3c0deadf to your computer and use it in GitHub Desktop.
export function Factory(getInstance?: boolean) {
return function (target: any) {
let construct: any = function (constructor: Function, args: any[]) {
var model: any = function () {
return constructor.apply(this, args);
}
Object.keys(constructor.prototype).forEach((key:string) => {
Object.defineProperty(model.prototype, key, Object.getOwnPropertyDescriptor(constructor.prototype, key));
});
return new model();
};
let componentConstructor: any = function (...args: any[]) {
var newInstance = construct(target, args);
if (componentConstructor.$inject) {
componentConstructor.$inject.forEach((el: string, index: number) => {
newInstance[el] = componentConstructor.injectors[index];
});
}
return newInstance;
};
componentConstructor.$inject = target.$inject;
componentConstructor.prototype = target.prototype;
let factoryFunction: any = (...args: any[]) => {
if (args.length) {
componentConstructor.injectors = args;
} else if (componentConstructor.$inject) {
let $injector: any = angular.injector(['ng']);
componentConstructor.injectors = [];
componentConstructor.$inject.forEach((el: string) => {
componentConstructor.injectors.push($injector.get(el));
});
}
if (getInstance) {
return new componentConstructor();
} else {
return componentConstructor
}
};
factoryFunction.$inject = target.$inject
return factoryFunction;
};
}
'use strict';
export function Inject(target:any, propertyKey: string): void {
if (!(target.constructor.$inject instanceof Array)) {
target.constructor.$inject = [];
};
target.constructor.$inject.push(propertyKey);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment