How can i count the number of errors on Form?

守給你的承諾、 提交于 2019-12-09 16:45:26

问题


FIDDLE

How can i count the number of errors made on form ?

HTML

 <div ng-show="form.$submitted && form.$invalid">
      Sorry but 3 errors have been made.
 </div>

回答1:


One way you could do this by using the specific count of a specific error criteria, required, pattern etc.. that are available as a part of form's $error[prop] array. In your case you could try using form.$error.required.length:-

<div ng-show="form.$submitted && form.$invalid">
       Sorry but {{form.$error.required.length}} errors have been made.
</div>

Demo

You could add a function on the controller which can determine the number of errors on the form and return it, and use it in the view to display the total error count.

 $scope.numberoferrors=function(form){
    var count = 0,
        errors = form.$error;

     angular.forEach(errors, function(val){ if(angular.isArray(val)) {  count += val.length; }  });
    //Object.keys(errors).forEach(function(key){ count += errors[key].length  }); //get count of all error categories from form

    return count;
 };

Demo



来源:https://stackoverflow.com/questions/26087123/how-can-i-count-the-number-of-errors-on-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!