How do I reset a form including removing all validation errors?

前端 未结 10 969
梦毁少年i
梦毁少年i 2020-12-14 01:59

I have an Angular form. The fields are validated using the ng-pattern attribute. I also have a reset button. I\'m using the Ui.Utils Event Binder to handle the

10条回答
  •  醉酒成梦
    2020-12-14 02:14

    There doesn't seem to be an easy way to reset the $errors in angular. The best way would probably be to reload the current page to start with a new form. Alternatively you have to remove all $error manually with this script:

    form.$setPristine(true);
    form.$setUntouched(true);
    
    // iterate over all from properties
    angular.forEach(form, function(ctrl, name) {
      // ignore angular fields and functions
      if (name.indexOf('$') != 0) {
        // iterate over all $errors for each field        
        angular.forEach(ctrl.$error, function(value, name) {
          // reset validity
          ctrl.$setValidity(name, null);
        });
      }
    });
    $scope.resetCount++; 
    

提交回复
热议问题