html – 如何重置表单,包括删除所有验证错误?
发布时间:2020-12-14 18:59:20 所属栏目:资源 来源:网络整理
导读:我有一个角度的形式.这些字段使用ng-pattern属性进行验证.我也有一个重置按钮.我正在使用 Ui.Utils Event Binder来处理重置事件,如下所示: form name="searchForm" id="searchForm" ui-event="{reset: 'reset(searchForm)'}" ng-submit="search()" div labe
我有一个角度的形式.这些字段使用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(); }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |