Define AngularJS directive using TypeScript and $inject mechanism

后端 未结 9 1707
死守一世寂寞
死守一世寂寞 2020-12-12 15:04

Recently I started refactoring one of the Angular projects I am working on with TypeScript. Using TypeScript classes to define controllers is very convenient and works well

9条回答
  •  轮回少年
    2020-12-12 15:35

    It's a bit late to this party. But here is the solution I prefer to use. I personally think this is cleaner.

    Define a helper class first, and you can use it anywhere.(It actually can use on anything if you change the helper function a bit. You can use it for config run etc. )

    module Helper{
        "use strict";
    
        export class DirectiveFactory {
            static GetFactoryFor(classType: Function): ng.IDirectiveFactory {
                var factory = (...args): T => {
                    var directive =  classType;
                    //return new directive(...args); //Typescript 1.6
                    return new (directive.bind(directive, ...args));
                }
                factory.$inject = classType.$inject;
                return factory;
            }
        }
    }
    

    Here is you main module

    module MainAppModule {
        "use strict";
    
    angular.module("App", ["Dependency"])
           .directive(MyDirective.Name, Helper.DirectiveFactory.GetFactoryFor(MyDirective));
    
        //I would put the following part in its own file.
        interface IDirectiveScope extends ng.IScope {
        }
    
        export class MyDirective implements ng.IDirective {
    
            public restrict = "A";
            public controllerAs = "vm";
            public bindToController = true;    
            public scope = {
                isoVal: "="
            };
    
            static Name = "myDirective";
            static $inject = ["dependency"];
    
            constructor(private dependency:any) { }
    
            controller = () => {
            };
    
            link = (scope: IDirectiveScope, iElem: ng.IAugmentedJQuery, iAttrs: ng.IAttributes): void => {
    
            };
        }
    }
    

提交回复
热议问题