0

How do I implement this in AngularJS 1.5.4 with TypeScript 1.6.2?

Here is the vanilla JavaScript version from the official docs: $compile#example

I've found this, but it doesn't work: Angularjs+Typescript directive implementing $compile

Here lies my current attempt:

export class Element implements angular.IDirective {
  public static ID = 'element';

  static $inject = ['$compile'];

  static factory(): angular.IDirectiveFactory {
    const directive = ($compile: ng.ICompileService) => new Element($compile);
    directive.$inject = Element.$inject;
    return directive;
  }

  constructor(private $compile: ng.ICompileService) {
  };

  link(scope: ng.IScope, element: any, attrs: any) {
    return scope.$watch(
      (scope: ng.IScope) => scope.$eval(attrs.compile),
      (value: string) => {
        element.html(value);
        this.$compile(element.contents())(scope);
      }
    );
  }

  link_old_attempt(scope: any, element: any, attrs: ng.IAttributes,
                   formCtrl: ng.IFormController) {
    const attr = scope.standard || scope.attrs || scope.ignore;
    element.html(this.$compile(attr));
    this.$compile(element.contents())(scope);
  }
}
5
  • Can you please provide your code? I am using the same syntax as in the article which you provided and it works as expected. Commented Apr 21, 2016 at 7:11
  • Can you trace Directive in your IDE to find where it is? - Maybe I need to import it. Commented Apr 21, 2016 at 7:14
  • Do not have any pure "Directive" in my solution... Maybe you are registering it incorrectly? In my solution i have separate module ts file and i import directive ts and then register it. Commented Apr 21, 2016 at 7:47
  • Hmm, not sure where I was getting Directive. Anyway, I've updated the question with my latest attempt. Commented Apr 21, 2016 at 8:06
  • Looks correct. Can you also provide code how you register it? Couple of notes: 1) you shouldn't return anything from link function. 2) Change your link function to lambda cause in other case you could have problems with 'this' context. Like this: link = (..) => {..} Commented Apr 21, 2016 at 8:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.