$watch仅在特定事件之后才查看属性

$watch an attribute only after certain event

本文关键字:之后 属性 事件 watch      更新时间:2023-09-26

我正在学习angular,我正在尝试构建一个表单:

1.on-blur检查属性值是否唯一。

2.如果该值不是唯一的,则它开始监视该值,并在用户键入时给出或删除表单上的错误。

我个人认为这种方式对用户更友好。键入时不会出现错误,但一旦出现错误,在进行更正时,错误就会消失。

这是我的代码:

$scope.checkUniqueValue = function(){
    var result = true;
    for(var i=0; i < $scope.users.length; i++ ){
        if($scope.users[i].name === $scope.userName){
            result = false;
            break;
        }
    }
    if(result){
        $scope.error = null;
    }else{
        $scope.error = "name is not unique";
        $scope.$watch( 'userName', function() {
            $scope.checkUniqueValue();
        });
    }
    return result;
};

它以应有的方式运行良好。然而,当我在chrome中打开开发人员工具时,我看到了所有这些错误:

Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.2.21/$rootScope/infdig?p0=10&p1=%5B%5B%22user…ned%22%5D%2C%5B%22userName%3B%20newVal%3A%20%5C%22akbar%5C%22%3B%20oldVal%...<omitted>...5D angular.js:36
Error: [$rootScope:infdig] http://errors.angularjs.org/1.2.21/$rootScope/infdig?p0=10&p1=%5B%5B%22user…me%3B%20newVal%3A%20%5C%22asghar%5C%22%3B%20oldVal%3A%20undefined%22%5D%5D
    at Error (native)
    at http://localhost:8080/bower_components/angular/angular.min.js:6:450
    at k.$digest (http://localhost:8080/bower_components/angular/angular.min.js:110:66)
    at k.$apply (http://localhost:8080/bower_components/angular/angular.min.js:112:173)
    at HTMLInputElement.l (http://localhost:8080/bower_components/angular/angular.min.js:136:370)
    at HTMLInputElement.n.event.dispatch (http://localhost:8080/bower_components/jquery/dist/jquery.min.js:3:6404)
    at HTMLInputElement.r.handle (http://localhost:8080/bower_components/jquery/dist/jquery.min.js:3:3179) angular.js:10023

我想知道是否有人知道这些错误的含义,以及我在这里做错了什么。由于代码有效,我很难找到导致它的问题。

我还想知道是否有更好的方法将$watch嵌套在if语句中,或者有更好的方式在不使用$watch的情况下实现这一点。

感谢

您得到的错误平均值为Infinite $digest Loop(请参阅文档)。

本质上是这样的:

    $scope.$watch( 'userName', function() {
        $scope.checkUniqueValue();
    });

总是会触发一个摘要循环,并且监视总是得到一个带有新值的初始化调用,无论该值是否已更改,所以一旦您达到以上的代码

        $scope.checkUniqueValue();

将始终被调用,由于没有任何更改,您定义了另一个手表,它将再次调用checkUniqueValue(),它将设置另一个表。。。循环将永远持续下去。

您应该将$watch从函数checkUniqueValue中移出,因为它不需要驻留在那里。