Angularjs + Typescript指令实现$ compile

Roc*_*oxx 5 angularjs typescript angularjs-directive

我在以下指令中注入$ compile时遇到问题.

export class Element {
    public link(scope:dirScopeInterface, element:any, attrs:ng.IAttributes, formCtrl:ng.IFormController) {
        var attr = this.arrayJoiner(scope.standard, scope.attrs || {}, scope.ignore || {});
        element.html(this.compiler(attr));
        $compile(element.contents())(scope);
    }
}
Run Code Online (Sandbox Code Playgroud)

目前它正在抛出$ compile是未定义的错误.我试过用

static $inject = ['$compile'];
Run Code Online (Sandbox Code Playgroud)

但由于某些原因,它从已编译的脚本中消失了.

是使用的完整代码.

dev*_*qon 9

包括static $injectconstructor:

export class Element {

    // $compile can then be used as this.$compile
    constructor(private $compile: ng.ICompileService){};

    public link(scope:dirScopeInterface, element:any, attrs:ng.IAttributes, formCtrl:ng.IFormController) {
        var attr = this.arrayJoiner(scope.standard, scope.attrs || {}, scope.ignore || {});
        element.html(this.compiler(attr));
        this.$compile(element.contents())(scope);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

要使用angular注册此指令,这就是我一直在做的(有多种解决方案):

export class Element implements angular.IDirective {

    public static ID = "element";

    // This can then be removed:
    // static $inject = ["$compile"];

    // ..

    /**
     * The factory function that creates the directive
     */
    static factory(): angular.IDirectiveFactory {
        const directive = ($compile) => new Element($compile);
        directive.$inject = ["$compile"];
        return directive;
    }
}
Run Code Online (Sandbox Code Playgroud)

并注册:

angular.module("myModule" [])
    .directive(Element.ID, Element.factory());
Run Code Online (Sandbox Code Playgroud)


Roc*_*oxx 0

所以我找到了一种让它工作的方法,但它并不像我希望的那么优雅。

angular.module('formDirectives', [], function($compileProvider){
    $compileProvider.directive('catElement', ($compile) => {
        return new Element($compile);
    });
})
Run Code Online (Sandbox Code Playgroud)