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

前端 未结 10 943
梦毁少年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:16

    You can add a validation flag and show or hide errors according to its value with ng-if or ng-show in your HTML. The form has a $valid flag you can send to your controller.

    ng-if will remove or recreate the element to the DOM, while ng-show will add it but won't show it (depending on the flag value).

    EDIT: As pointed by Michael, if form is disabled, the way I pointed won't work because the form is never submitted. Updated the code accordingly.

    HTML

    The area code must be three digits
    The phone number must be seven digits

    JS

    $scope.search = function() {
        alert('Searching');
    };
    
    $scope.reset = function(form) {
         form.$setPristine();
         form.$setUntouched();
         $scope.resetCount++;
     };
    

    Codepen with working solution: http://codepen.io/anon/pen/zGPZoB

提交回复
热议问题