使用类并继承 ng.IDirective 是使用 TypeScript 的方法。
TypeScript 包含对粗箭头函数的支持() =>
来自 EcmaScript 6。
这是一种速记语法,也改变了this
关键词作品:
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) => {
console.log(this); // this points to MyDirective instance instead of Window
elem.bind('blur', (evt: JQueryEventObject) => {
console.log(this); // this points to MyDirective instance instead of Window
this.validate();
});
}
validate() {
console.log(this); // this points to MyDirective instance instead of Window
}
static factory(): ng.IDirectiveFactory {
var directive = (myFactory: app.services.MyFactory) => new MyDirective(myFactory);
directive.$inject = ['myFactory'];
return directive;
}
}
app.directive('mydirective', MyDirective.factory());
你也可以依靠旧时尚var self = this;
图案:
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) => {
console.log(this); // this points to MyDirective instance instead of Window
var self = this;
function validate() {
console.log(self); // self points to MyDirective instance
}
elem.bind('blur', function(evt: JQueryEventObject) {
console.log(self); // self points to MyDirective instance
validate();
});
}
}
相关回答:https://stackoverflow.com/a/29223535/990356 https://stackoverflow.com/a/29223535/990356