Angularjs 这在es6指令中为空
在类构造函数调用指令的link函数后,我用es6编写指令(并用babel编译),但由于某种原因,Angularjs 这在es6指令中为空,angularjs,angularjs-directive,ecmascript-6,babeljs,Angularjs,Angularjs Directive,Ecmascript 6,Babeljs,在类构造函数调用指令的link函数后,我用es6编写指令(并用babel编译),但由于某种原因,this为空 代码段: class AutoSaveDirective { constructor($timeout) { this.restrict = 'EA'; this.require = '^form'; this.$timeout = $timeout; this.scope = { auto
this
为空
代码段:
class AutoSaveDirective {
constructor($timeout) {
this.restrict = 'EA';
this.require = '^form';
this.$timeout = $timeout;
this.scope = {
autoOnSave: '&',
autoSaveDebounce: '='
}
}
link(scope, el, attr, formCtrl) {
scope.$watch(()=> {
console.log('form changed, starting timout');
if (!formCtrl.$dirty) {
return;
}
at this line ==>if(this.currentTimeout){
console.log('old timeout exist cleaning');
this.currentTimeout.cancel();
this.currentTimeout = null;
}
console.log('starting new timeout');
this.currentTimeout = $timeout(()=>{
console.log('timeout reached, initiating onsave')
scope.autoOnSave();
}, scope.autoSaveDebounce);
});
}
}
angular.module('sspApp').directive('autoSave', () => new AutoSaveDirective());
由于angular调用它的方式,您必须将链接函数绑定到类
class AutoSaveDirective {
constructor($timeout) {
//...
this.link = this.unboundLink.bind(this);
}
unboundLink(scope, el, attr, formCtrl) {
scope.$watch(()=> {
//...
});
}
}
如果您想将类与angular一起使用,更好的方法是将它们用于控制器,并使用controllerAs语法。e、 g
angular.module('sspApp').directive('autoSave', function() {
return {
restrict: 'EA',
scope: {
autoOnSave: '&',
autoSaveDebounce: '=',
formCtrl: '='
},
bindToController: true,
controller: AutoSave,
controllerAs: 'ctrl'
};
});
class AutoSave {
constructor() {
//Move logic from link function in here.
}
}
由于angular调用它的方式,您必须将链接函数绑定到类
class AutoSaveDirective {
constructor($timeout) {
//...
this.link = this.unboundLink.bind(this);
}
unboundLink(scope, el, attr, formCtrl) {
scope.$watch(()=> {
//...
});
}
}
如果您想将类与angular一起使用,更好的方法是将它们用于控制器,并使用controllerAs语法。e、 g
angular.module('sspApp').directive('autoSave', function() {
return {
restrict: 'EA',
scope: {
autoOnSave: '&',
autoSaveDebounce: '=',
formCtrl: '='
},
bindToController: true,
controller: AutoSave,
controllerAs: 'ctrl'
};
});
class AutoSave {
constructor() {
//Move logic from link function in here.
}
}
link
函数由compile
函数返回,它作为函数而不是方法调用。因此,您可以定义编译
而不是链接
方法:
compile() {
return (scope, el, attr, formCtrl) => { ... };
}
话虽如此,将指令定义为类是没有价值的。链接函数是由
编译
函数返回的,它是作为函数调用的,而不是作为方法调用的。因此,您可以定义编译
而不是链接
方法:
compile() {
return (scope, el, attr, formCtrl) => { ... };
}
话虽如此,将指令定义为类是没有价值的