angularjs - 如何在 TypeScript 中实现 ng.IDirectiveFactory

标签 angularjs angularjs-directive typescript

我最近更新了我的 typescript 项目中的 angular.d.ts 文件。我现在在我的指令定义中遇到 typescript 编译错误。我在更新的 angular.d.ts 文件中注意到以下内容:

interface IDirectiveFactory {
    (...args: any[]): IDirective;
}

我正在尝试弄清楚如何实现这个接口(interface)。

我收到此编译器错误:类型 ng.DirectiveFactory 需要调用签名,但类型“MyDirective”缺少调用签名。

这就是我的指令现在的样子(过去可以很好地处理旧的 angular.d.ts 文件):

class MyDirective{
    constructor() {
        var directive: ng.IDirective = <ng.IDirective>{};
        directive.priority = 0;
        directive.restrict = "E";
        directive.scope = {...};
        directive.template = '<div></div>';
        directive.link = {...}
        return directive;
    }
}

这是我用 angular 注册 MyDirective 类的地方:

angular.module("MyModule", [])
        .directive('myDirective', MyDirective);

上面的编译器错误很有意义,但我该如何实现 (...args: any[]): IDirective 签名)?

提前致谢

最佳答案

我知道这是一个老问题,但我也遇到过这个问题并认为我会分享我的解决方案:

class MyDirective implements ng.IDirective {
    priority = 0;
    restrict = 'E';
    scope = {...};
    template = '<div></div>';

    link(scope: ng.IScope
        , element: ng.IAugmentedJQuery
        , attributes: IAttributes
        , controller: any
        , transclude: ng.ITranscludeFunction) {
        ...
    }
}

angular.module("MyModule", [])
    .directive('myDirective', () => new MyDirective());

我喜欢这个解决方案,因为它允许您使用 TypeScript 类的全部优势。

更新 如果您想使用这种方法使用私有(private)类函数或字段来简化您的链接函数,您将需要稍微不同地定义您的链接函数:

class MyDirective implements ng.IDirective {
    priority = 0;
    restrict = 'E';
    scope = {...};
    template = '<div></div>';

    link = (scope: ng.IScope
        , element: ng.IAugmentedJQuery
        , attributes: IAttributes
        , controller: any
        , transclude: ng.ITranscludeFunction) => {
        ...
    }
}

angular.module("MyModule", [])
    .directive('myDirective', () => new MyDirective());

(注意链接方法在这里声明为粗箭头函数而不是类函数)

这是因为当 Angular 连接它时,它以一种不保留类的 this 引用的方式进行连接。通过使用粗箭头函数定义它,编译后的 JavaScript 将以保留 this 引用的方式定义函数。否则,您将在尝试运行代码时遇到很多错误。

关于angularjs - 如何在 TypeScript 中实现 ng.IDirectiveFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25215410/

相关文章:

javascript数组整理并显示多维

javascript - AngularJS 服务问题

javascript - $scope 未定义 - codepen

javascript - AngularJS 循环通过 http get req 找到正确的 url

angularjs - 使用 ngModel 和普通 ngController 而不是指令?

通用 `keyof` `extends keyof` `typeof` 和其他的 Typescript 混淆

typescript - TypeScript 中 protected 的等价物是什么?

angular - 为什么服务错误以字符串而不是 json 对象的形式发送回来?

javascript - ng-repeat 内的输入文本框验证

javascript - 为什么我的指令抛出 "Error: $injector:unpr Unknown Provider"