1

编辑/更新:

我忘记了 angular 1.6 中的原始代码(正常方式):

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

我想,这可以帮助你。我的工作是在 EcmaScript ES6 中进行转换。


谁的工作很棒!

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

  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:无法读取未定义的属性“ui”

还有一个问题:$watchContoller构造函数中不应该设置函数吗?

4

3 回答 3

7

您直接调用函数而不是在第二个参数中传递函数引用。

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

或者

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

你也可以写成很简单的形式

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

但是你必须以箭头函数格式编写底层函数

resetUiCheck = (newValue, oldValue) => 
   this.resetUiCheck( newValue, oldValue)
);
于 2017-03-13T15:49:56.023 回答
2

它应该是:

this.$scope.$watch('ui.shake', this.resetUiCheck)
于 2017-03-13T15:51:14.477 回答
1

首先,永远不要在控制器中使用 $watch。其次,你不需要$watch。

$scope.ui.shake = true;
$timeout(function(){
    $scope.ui.shake = false;
}, 1000);
于 2017-03-22T10:45:31.143 回答