Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs+Typescript directive implementing $compile

I am having issues injecting $compile in the following directive.

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);
    }
}

At the moment it is throwing an $compile is undefined error. I have tried using

static $inject = ['$compile'];

But it disappears from the transpiled script for some reason.

Here is the full code used.

like image 956
Rockroxx Avatar asked Jun 09 '15 09:06

Rockroxx


1 Answers

Include the static $inject and a constructor:

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);
    }
}

EDIT

To register this directive with angular, this is what I always do (there are multiple solutions):

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;
    }
}

and to register:

angular.module("myModule" [])
    .directive(Element.ID, Element.factory());
like image 99
devqon Avatar answered Oct 20 '22 13:10

devqon