【问题标题】:Get Angular directive name from TypeScript从 TypeScript 获取 Angular 指令名称
【发布时间】:2016-07-02 04:20:23
【问题描述】:

我实现了下一个 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());
    }        
}

是否可以在不将指令名称传递给工厂函数的情况下在链接函数中获取指令名称(我不想重复指令名称)?

【问题讨论】:

    标签: angularjs angularjs-directive typescript


    【解决方案1】:

    你可以在变量外部有指令名称,这样它就可以在内部的任何地方访问。

    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 来获取指令名称。

    【讨论】:

    • 是的,你是对的,我可以。但在这种情况下,我得到了一种我想避免的共享/全局变量。我会澄清我的问题。不过,感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 2018-06-24
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多