I ran into the same problem and solved it by implementing a Util class called "ComponentRegistrator" (inspired by the comments on this page ):
/// <reference path="../../../Typings/tsd.d.ts"/> module Common.Utils { "use strict"; export class ComponentRegistrator { public static regService(app: ng.IModule, name: string, classType: Function) { return app.service(name, classType); } public static regController(app: ng.IModule, name: string, classType: Function) { var factory: Function = Component.reg(app, classType); return app.controller(name, factory); } public static regDirective(app: ng.IModule, name: string, classType: Function) { var factory: Function = Component.reg(app, classType); return app.directive(name, <ng.IDirectiveFactory>factory); } private static reg<T extends ng.IDirective>(app: ng.IModule, classType: Function) { var factory: Function = (...args: any[]): T => { var o = {}; classType.apply(o, args) || console.error("Return in ctor missing!"); return <T> o; }; factory.$inject = classType.$inject || []; return factory; } } }
And it can be, for example, can be used as follows:
/// <reference path="../../../Typings/tsd.d.ts"/> ///<reference path="../../Common/Utils/Component.ts"/> module Sample { "use strict"; class SampleDirective implements ng.IDirective { public static $inject: string[] = []; public templateUrl: string; public scope: {}; public restrict: string; public require: string; public link: ng.IDirectiveLinkFn; constructor() { this.templateUrl = "/directives/sampleDirective.html"; this.restrict = "A"; this.scope = { element: "=", }; this.link = this.linker; return this; // important! } private linker = (scope: IExpressionConsoleScope): void => { // ... }; } ComponentRegistrator.regDirective(app, "directiveName", SampleDirective); }
Notice the return this in the constructor and static $inject . You will need to specify the injection as described in the PSL:
// ... class SampleDirective implements ng.IDirective { public static $inject: string[] = ["$timeout"]; // ... constructor(private $timeout:ng.ITimeoutService) { // ...
This way duplication of the factory method can be avoided, and you can always use the same template ...
source share