为什么"这个" null,在Angular Directive中的link函数中?

时间:2016-01-02 00:19:03

标签: javascript angularjs typescript 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),
        ]);
}

2 个答案:

答案 0 :(得分:3)

我似乎使用了错误的语法来处理链接功能。这是正确的实施:

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

任何人都能解释为什么会这样吗? : - )

答案 1 :(得分:1)

你需要:

    .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问题的要点是当角度调用link起作用时,不会保留此上下文。

如果您想更深入地了解这个问题,只需使用angular.js代替angular.min.js,看看调用堆栈是什么样的。