Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "this" null, in the link function within an Angular Directive?

I'm trying to write a dynamic template using TypeScript and Angular, however for some reason the 'this' keyword is always null, thus I cannot access my private member $compile. Any ideas? Many Thanks! :-)

Directive:

namespace ROD.Features.Player {
    "use strict";

    export class VideoDirective implements ng.IDirective {
        public restrict: string = "E";
        public replace: boolean = true;
        public scope = {
            content: "="
        };

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

        public link(element: JQuery, scope: ng.IScope): any {
            const youtubeTemplate = "<p>Youtube</p>";
            const vimeoTemplate = "<p>Vimeo</p>";

            var linkFn = this.$compile(youtubeTemplate);
            const content: any = linkFn(scope);
            element.append(content);
        }
    }
}

App.ts:

namespace ROD {
    "use strict";
    angular.module("rodApp", [])
        .service("Settings", [() => new Settings.DevelopmentSettings()])
        .service("RedditService", [
            "$http", "Settings",
            ($http: ng.IHttpService, settings: Settings.ISettings) => new Services.Reddit.RedditService($http, settings.sourceUrl),
        ])
        .directive("videoItem", ["$compile",
            ($compile: ng.ICompileService) => new Features.Player.VideoDirective($compile)])
        .controller("PlayerController", [
            "$scope", "RedditService",
            ($scope: any, redditService: Services.Reddit.IRedditService) => new Features.Player.PlayerController($scope, redditService),
        ]);
}
like image 815
Adrian Luca Thomas Avatar asked Sep 26 '22 19:09

Adrian Luca Thomas


1 Answers

It appears that I was using the wrong syntax for the link function. This is the correct implementation:

        public link = (element: JQuery, scope: ng.IScope): any => {
            const youtubeTemplate = "<p>Youtube</p>";
            const vimeoTemplate = "<p>Vimeo</p>";

            var linkFn = this.$compile(youtubeTemplate);
            const content: any = linkFn(scope);
            element.append(content);
        }

Can anyone explain why this is? :-)

like image 174
Adrian Luca Thomas Avatar answered Oct 11 '22 06:10

Adrian Luca Thomas