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

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

    I started with the comment from @Brett and built upon it. I actually have multiple forms and each form has many fields (more than just the two shown). So I wanted a general solution.

    I noticed that the Angular form object has a property for each control (input, select, textarea, etc) as well as some other Angular properties. Each of the Angular properties, though, begins with a dollar sign ($). So I ended up doing this (including the comment for the benefit of other programmers):

    $scope.reset = function(form) {
        // Each control (input, select, textarea, etc) gets added as a property of the form.
        // The form has other built-in properties as well. However it's easy to filter those out,
        // because the Angular team has chosen to prefix each one with a dollar sign.
        // So, we just avoid those properties that begin with a dollar sign.
        let controlNames = Object.keys(form).filter(key => key.indexOf('$') !== 0);
    
        // Set each control back to undefined. This is the only way to clear validation messages.
        // Calling `form.$setPristine()` won't do it (even though you wish it would).
        for (let name of controlNames) {
            let control = form[name];
            control.$setViewValue(undefined);
        }
    
        form.$setPristine();
        form.$setUntouched();
    };
    

提交回复
热议问题