this 在 es6 的指令中为 null

this is null in directive with es6

在 class 构造函数 angular 调用指令的 link 函数之后,我正在用 es6 编写指令(并用 babel 编译它)但是由于某种原因 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 调用它的方式,您必须将 link 函数绑定到 class。

class AutoSaveDirective {
    constructor($timeout) {
        //...

        this.link = this.unboundLink.bind(this);
    }

    unboundLink(scope, el, attr, formCtrl) {
        scope.$watch(()=> {
            //...
        });
    }
}

如果您想将 classes 与 angular 一起使用,更好的方法是将它们用于控制器并使用 controllerAs 语法。例如

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 而不是 link 方法:

compile() {
  return (scope, el, attr, formCtrl)  => { ... };
}

话虽如此,将指令定义为 class 没有任何价值。