2014-08-27 72 views
0

我正在学习角度,我正试图构建一个表单:

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 

我想知道是否有人知道这些错误是什么意思,什么我做错了here.since代码工作,这对我来说是困难找出导致它的问题。

另外我想知道是否有一个更好的方法来嵌套$ watch内if语句或有更好的方法来处理这个没有使用$ watch。

谢谢

+0

[ngChange](https://docs.angularjs.org/api/ng/directive/ngChange)是你的朋友。 – 2014-08-27 22:16:01

+0

是否有限制ng-change只有在模糊上出现错误后才开始工作?但如果在模糊上没有错误,ng-change仍然被禁用? – 2014-08-27 22:21:38

+0

为什么你会希望事先显示错误然后等待表单提交。你可以做的一件事是设置输入文本数量的基本限制。也就是说,如果用户键入了超过3个字符,则只会显示错误 – 2014-08-27 22:24:56

回答

1

你得到的错误意味着Infinite $digest Loopsee docs)。

本质上这:

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

总是会引发消化循环,手表总是与新值的初始化调用,不管该值是否有变化,所以一旦你达到上述

代码
 $scope.checkUniqueValue(); 

将永远被调用,因为什么事都没有改变你定义另一个手表,再次将调用checkUniqueValue(),这将设置其他的手表......和循环继续下去。

0

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

相关问题