gpt4 book ai didi

javascript - 为什么 "this"在 Angular 指令中的链接函数中为空?

转载 作者:搜寻专家 更新时间:2023-10-30 20:43:00 25 4
gpt4 key购买 nike

我正在尝试使用 TypeScript 和 Angular 编写一个动态模板,但是由于某种原因,“this”关键字始终为 null,因此我无法访问我的私有(private)成员 $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);
}
}
}

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

最佳答案

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

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

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

关于javascript - 为什么 "this"在 Angular 指令中的链接函数中为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34561415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com