我有一个角度的形式.这些字段使用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的建议.我添加计数器的唯一原因是证明代码正在被调用(它是).
解决方法
我从@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(); };