我正在尝试使用TypeScript创建一个AngularJS指令。我的指令需要'ngModel',我也使用了我的指令中注入的自定义服务。 我的主要问题是我的服务无法在我的链接功能中使用。AngularJS TypeScript指令链接功能
这里是我想要达到一个例子:
module app.directives {
export var directiveName: string = "theDirective";
angular.module("myApp").directive(directiveName,
(myFactory: app.services.MyFactory) =>
{
return new MyDirective(myFactory);
});
export interface IMyDirectiveScope extends ng.IScope {
ngModel: ng.INgModelController;
}
export class MyDirective implements ng.IDirective {
restrict = "A";
require = "ngModel";
scope = {
ngModel:'='
}
constructor(private myFactory: app.services.MyFactory) {
}
link(scope: IMyDirectiveScope , elem: JQuery, attributes: ng.IAttributes, ngModel: ng.INgModelController) {
//this is window here
elem.bind('blur', (evt: JQueryEventObject) => {
//keyword this is also window here, so yeah bummer indeed
validate();
});
function validate() {
//I need to use my factory here, but I can seem to get it.
//this is always window and I'm kinda stuck here
}
}
}
}
我似乎无法找到有关这个主题的一些更高级的东西。所有的例子我都不觉得似乎没有使用服务或复杂的链接功能。 请用某种例子回答这个问题。你认为这是骗人的。
更新:在我的链接函数中的'this'是窗口而不是'MyDirective'的事实对我来说没有多大意义。任何想法为什么会这样?
钍这是有效的,你能举一个例子,你如何在没有课堂的情况下处理这种情况? – user1613512
@ user1613512我编辑了我的答案,以包含一个没有类的例子 – rob
Write unboundLink(...){var self = this; ...}那么你可以在validate()中使用self变量而不是这个。 –