Why is "this" null in the link function in the Angular directive?

I am trying to write a dynamic template using TypeScript and Angular, however for some reason the keyword 'this' is always null, so 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),
        ]);
}
+4
source share
2 answers

It looks like I used 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 someone explain why this is ?:-)

+3
source

You need:

    .directive("videoItem", ["$compile",
    function ($compile) { return () => new ROD.Features.Player.VideoDirective($compile); }])

instead

    .directive("videoItem", ["$compile",
    function ($compile) { return new ROD.Features.Player.VideoDirective($compile); }])

app.js. : http://www.michaelbromley.co.uk/blog/350/exploring-es6-classes-in-angularjs-1-x#_section-directives , angular link, .

, angular.js angular.min.js , .

+1

Source: https://habr.com/ru/post/1622482/


All Articles