我有一个简单的表单,我在包含数字值的输入框上应用了AngularJS验证。提交时,它工作正常,但当我单击重置按钮时,它会给出输入框验证错误消息。在点击重置按钮后,看起来它正在调用ng-submit。我尝试在ng-click中重置输入字段的值,删除type ='Reset'并在表单上使用$ setPristine()。但没有任何帮助。以下是代码。
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button ng-click="reset(myForm)">
Reset
</button>
</form>
控制器:
var original = $scope.age;
$scope.submitFilter = function () {
if ($scope.filterForm.$valid) {
} else {
$scope.submitted = true;
}
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
请帮助摆脱这个错误。 在此先感谢。
答案 0 :(得分:1)
将重置按钮的类型设置为&#39;按钮&#39;应该管用。以下代码在我的机器上完美运行。
// Code goes here
app.controller('mainController', function($scope) {
$scope.age = 123;
var original = $scope.age;
$scope.submitFilter = function () {
$scope.submitted = true;
};
$scope.reset = function (myForm) {
$scope.age = angular.copy(original);
$scope.myForm.$setPristine();
};
});
<form name="myForm" novalidate ng-submit="submitFilter()">
Enter Age:
<div>
<input name="age" ng-class="{errorinput: submitted && myForm.age.$invalid }" class="form-control" ng-pattern="/^[0-9]+$/" placeholder="Age" type="text" ng-model="age" required>
</div>
<span class="error" ng-style="{color:'red'}" ng-show="submitted && myForm.age.$invalid">Please enter a valid Age</span>
<button type="submit">
Submit
</button>
<button type="button" ng-click="reset(myForm)">
Reset
</button>
</form>