2017-03-13 51 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);