为什么在 Angular 指令中的 link 函数中 "this" 为空?

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

我正在尝试使用 TypeScript 和 Angular 编写动态模板,但是由于某种原因,'this' 关键字始终为 null,因此我无法访问我的私有成员 $compile。有任何想法吗?非常感谢! :-)

指令:

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

您需要:

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

而不是

    .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 函数时,不会保留 this 的上下文。

如果您想更深入地了解问题 in-depth,只需使用 angular.js 而不是 angular.min.js 并查看调用堆栈的样子。

看来我对 link 函数使用了错误的语法。这是正确的实现:

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

谁能解释这是为什么? :-)