我有一个非常大的形式,由Angular在客户端验证。我试图找出如何重置窗体的状态及其输入只需单击重置按钮。
我在表单上尝试了$setPristine()
,但它并没有真正起作用,这意味着它不会清除ng-*
类,无需执行验证即可将表单重置为原始状态。< / p>
这是我的表单的简短版本:
<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
设置为上面定义的内容不会因某种原因重置字段。
答案 0 :(得分:1)
尝试通过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: ""
};
}
答案 1 :(得分:0)
如评论中所述,您可以使用$setUntouched();
https://docs.angularjs.org/api/ng/type/form.FormController# $ setUntouched
这应该将表格设置回它的新状态。
所以在这种情况下$scope.create.$setUntouched();
应该做的伎俩
参考所有jquery。您永远不应该通过控制器与DOM交互。
的指令是什么如果要重置给定的属性,请执行以下操作:
$scope.resetProject = function() {
$scope.project = {
state: "finished",
topic: "Home automation"
};
$scope.project.lastName = '';
$scope.project.date= '';
}