为什么是“这个"?null,在 Angular 指令中的链接函数中? [英] Why is "this" null, in the link function within an Angular Directive?
本文介绍了为什么是“这个"?null,在 Angular 指令中的链接函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 TypeScript 和 Angular 编写动态模板,但是由于某种原因,this"关键字始终为空,因此我无法访问我的私有成员 $compile.有任何想法吗?非常感谢!:-)
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! :-)
指令:
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),
]);
}
推荐答案
看来我对链接函数使用了错误的语法.这是正确的实现:
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? :-)
这篇关于为什么是“这个"?null,在 Angular 指令中的链接函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文