2017-03-13 54 views
1

編輯/更新:

我忘了我的角1.6(正常方式)原代碼:

http://codepen.io/darkiron/pen/qRJmaj

我想,這可能helpe你。 我的工作是在EcmaScript ES6中轉換。


誰工作很棒!

如何在ES6中使用$watch角度控制器?

loginaction(){ 

    this.$scope.$watch('ui.shake', this.resetUiCheck()); 
    .... 
} 

我試試這個,結果預計不會

resetUiCheck(newValue, oldValue){  
    console.log(this.ui.shake); 
    return() => { 
     alert('foo'); 
     console.log(this); 
     if(this.ui.shake == true){ 
      this.$timeout(function(){ 
       this.ui.shake = false; 
      }, 1000); 
     } 
    }; 

} 

回報總是假的!

我試試這個:

this.$scope.$watch('ui.shake', this.resetUiCheck); 

,結果是這個錯誤

TypeError: Cannot read property 'ui' of undefined

另一個問題:$watch函數不應該在控制器上的構造函數來設置?

+1

1.爲什麼'$ watch'呢? 2.爲什麼'超時'? 3.你的意思是「迴歸總是假的」_? – zeroflagL

+0

閱讀[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 – georgeawg

+0

另請參見[AngularJs 1.5 - 組件不支持Watchers,什麼是解決方法?](http://stackoverflow.com/questions/35534479/angularjs-1-5-component-does-not-support-watchers-what -is-the-work-around/35535336) – georgeawg

回答

5

您直接調用函數而不是在第二個參數中傳遞函數引用。

this.$scope.$watch('ui.shake',this.resetUiCheck.bind(this)); 

OR

this.$scope.$watch('ui.shake', (newValue, oldValue) => 
    this.resetUiCheck(newValue, oldValue) 
); 
2

它應該是:

this.$scope.$watch('ui.shake', this.resetUiCheck) 
1

首先,千萬不要使用$觀看控制器。其次,你不需要$ watch。

$scope.ui.shake = true; 
$timeout(function(){ 
    $scope.ui.shake = false; 
}, 1000);