2015-12-02 55 views
0

我正在用es6編寫指令(並且用babel編譯它)後類構造函數角度調用指令的鏈接函數,但由於某些原因this爲空。在es6指令中爲null

代碼片段:

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()); 

回答

4

你得你的鏈接功能的方式綁定到類,由於該角調用它。

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

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

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

如果要使用具有角度的類,更好的方法是將它們用於控制器並使用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. 
    } 
} 
0

link功能由compile函數返回,這就是所謂的功能,而不是一個方法。所以,你可以定義一個compile代替link方法:

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

說了這麼多,有一個在定義一個指令爲一類沒有價值。