从TypeScript获取Angular指令名称

时间:2016-03-16 10:33:16

标签: angularjs angularjs-directive typescript

我实现了下一个AngularJS指令:

export module Directives {

    export class PasswordsMatch implements ng.IDirective {

        public static Factory(name: string) : ng.IDirectiveFactory {
            return () => new PasswordsMatch();
        }

        require = 'ngModel';            
        link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: Attributes): void => {
            // how to get directive name here?
        };
    }
}

在另一个脚本文件中注册为:

class Application {
    private app: ng.IModule;

    constructor() {     

        // Controllers

        // Directives           
        this.app.directive('ngPasswordsMatch', Directives.PasswordsMatch.Factory());
    }        
}

是否可以在链接函数中获取指令名称而不将指令名称传递给Factory函数(我不想复制指令名称)?

1 个答案:

答案 0 :(得分:0)

您可以在变量中包含指令名称,以便可以在任何位置访问它。

let directiveName = 'ngPasswordsMatch'; //declared directive name as string
export module Directives {

  export class PasswordsMatch implements ng.IDirective {

    public static Factory(name: string): ng.IDirectiveFactory {
      return () => new PasswordsMatch();
    }

    require: 'ngModel';
    link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: Attributes): void => {
      console.log(directiveName); //directive name accessible here
    };
  }
}

this.app.directive(directiveName, Directives.PasswordsMatch.Factory());

通过使用变量directiveName来获取指令名称。