Why is “this” null, in the link function within an

2019-06-21 18:18发布

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

2条回答
叼着烟拽天下
2楼-- · 2019-06-21 18:41

You need to have:

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

instead of

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

in your app.js. An explanation of the problem is here: http://www.michaelbromley.co.uk/blog/350/exploring-es6-classes-in-angularjs-1-x#_section-directives The gist of the problem is that when angular calls link function, the context of this is not preserved.

If you want to understand the issue more in-depth, just use angular.js instead of angular.min.js and have a look what the call stack looks like.

查看更多
戒情不戒烟
3楼-- · 2019-06-21 18:56

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? :-)

查看更多
登录 后发表回答