【发布时间】:2015-12-08 00:47:53
【问题描述】:
我有一个非常大的表单,正在由 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 设置为上面定义的内容不会出于某种原因重置字段。
【问题讨论】:
-
“它真的没用”是什么意思?。
-
另外,获取 plnkr 来显示您的问题也会很有用。
-
它不会清除
ng-*类以将表单重置为其原始状态而不执行验证 -
您尝试过
$scope.create.$setUntouched();- 取决于您使用的版本。 -
@Darren 你是个天才,这正是我想要的。我想我把这个功能搞砸了
$setPristine()所做的。发布为答案,我会接受它:)
标签: javascript angularjs forms