微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 如何重置表单,包括删除所有验证错误?

我有一个角度的形式.这些字段使用ng-pattern属性进行验证.我也有一个重置按钮.我正在使用 Ui.Utils Event Binder来处理重置事件,如下所示:
<form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()">
  <div>
    <label>
      Area Code
      <input type="tel" name="areaCode" ng-model="areaCode" ng-pattern="/^([0-9]{3})?$/">
    </label>

    <div ng-messages="searchForm.areaCode.$error">
      <div class="error" ng-message="pattern">The area code must be three digits</div>
    </div>
  </div>

  <div>
    <label>
      Phone Number
      <input type="tel" name="phoneNumber" ng-model="phoneNumber" ng-pattern="/^([0-9]{7})?$/">
    </label>

    <div ng-messages="searchForm.phoneNumber.$error">
      <div class="error" ng-message="pattern">The phone number must be seven digits</div>
    </div>
  </div>

  <br>
  <div>
    <button type="reset">Reset</button>
    <button type="submit" ng-disabled="searchForm.$invalid">Search</button>
  </div>
</form>

正如你所看到的,当表单被重置时,它调用$scope上的reset方法.以下是整个控制器的外观:

angular.module('app').controller('mainController',function($scope) {
    $scope.resetCount = 0;

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

    $scope.search = function() {
        alert('Searching');
    };
});

我正在调用form $setPristine()和form.$setUntouched,遵循从another question这里的Stack Overflow的建议.我添加计数器的唯一原因是证明代码正在被调用(它是).

问题是,即使在重置表单之后,验证消息也不会消失.您可以在Plunker看到完整的代码.这是一个截图,显示错误不会消失:

解决方法

我从@Brett的评论开始,并建立在它的基础之上.我实际上有多个表单,每个表单有很多字段(不仅仅是两个表单).所以我想要一个通用的解决方案.

我注意到Angular form对象具有每个控件的属性(input,select,textarea等)以及一些其他Angular属性.然而,每个Angular属性都以美元符号($)开头.所以我最终这样做(包括对其他程序员的好处的评论):

$scope.reset = function(form) {
    // Each control (input,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();
};

原文地址:https://www.jb51.cc/html/224584.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐