我有一个相当大的表单,正在客户端由 Angular 进行验证。我试图找出如何重置表单的状态及其输入,只需单击“重置”按钮即可。
我已经在表单上尝试了 $setPristine()
但它并没有真正起作用,这意味着它没有清除 ng-*
类来重置表单恢复到其原始状态,未执行任何验证。
这是我的表单的简短版本:
<form id="create" name="create" ng-submit="submitCreateForm()" class="form-horizontal" novalidate>
<div class="form-group">
<label for="name" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input required type="text" ng-model="project.name" name="name" class="form-control">
<div ng-show="create.$submitted || create.name.$touched">
<span class="help-block" ng-show="create.name.$error.required">Name is required</span>
</div>
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-md-3 control-label">Last name</label>
<div class="col-md-9">
<input required type="text" ng-model="project.lastName" name="lastName" class="form-control">
<div ng-show="create.$submitted || create.lastName.$touched">
<span class="help-block" ng-show="create.lastName.$error.required">Last name is required</span>
</div>
</div>
</div>
<button type="button" class="btn btn-default" ng-click="resetProject()">Reset</button>
</form>
还有我的重置功能:
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$("#create input[type='email']").val('');
$("#create input[type='date']").val('');
$scope.selectedState = $scope.project.state;
// $scope.create.$setPristine(); // doesn't work
}
此外,如果您可以帮助我在不使用 jQuery 的情况下清除电子邮件和日期字段的输入值,那就太好了。因为将 $scope.project
设置为上面定义的内容不会由于某种原因重置字段。
最佳答案
尝试通过ng-model清除
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$("#create input[type='email']").val('');
$("#create input[type='date']").val('');
$scope.selectedState = $scope.project.state;
$scope.project = {
name: "",
lastName: ""
};
}
关于javascript - AngularJS 完全重置表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34138548/