我正在尝试使用 Angular 的内置表单函数,特别是setPristine()
清除用户提交时的表单。我的控制器可以访问$scope.newForm
(我的形式)及其所有方法,但正在运行$scope.newForm.$setPristine()
没有重置表单字段。
这是我的 HTML:
<div ng-controller="NewFormController">
<h3>New Entry</h3>
<form name="newForm" method="post" novalidate>
<div class="input-group">
<label>Name</label>
<input name="name" type="text" ng-model="place.name"/>
</div>
<div class="input-group">
<label>Description</label>
<textarea name="description" type="text" ng-model="place.description"></textarea>
</div>
<div class="input-group">
<label>Neighborhood</label>
<input name="neighborhood" type="text" ng-model="place.neighborhood"/>
</div>
<div class="input-group">
<label>Address</label>
<input name="location" type="text" ng-model="place.address"/>
</div>
<input type="submit" value="Submit" ng-click="submit(place)"/>
</form>
</div>
这是我调用的控制器setPristine()
:
app.controller('NewFormController', function($scope, $compile) {
$scope.place = {
name: 'ExamplePlace',
description: 'This is a description!',
neighborhood: 'Manhattan',
address: '112 Street Place'
};
$scope.submit = function(place) {
$scope.newForm.$setPristine();
$scope.newForm.$setUntouched();
};
});
这是一个工作代码笔这重现了我的问题。
注意:我使用的是 Angular 版本 1.4.3。
$setPristine
仅将表单标记为$pristine
,这对于验证驱动的表达式和 CSS 很有用(例如.ng-dirty
)
So, $setPristine
不清除表单的控件。其实它根本就不知道how要做到这一点。考虑一下,“清晰”对于不同的模型可能意味着不同的事情。 “清晰”可能意味着""
, or undefined
, or null
,或者任何与自定义输入控件一起使用的东西ngModel
可能意味着。
因此,要正确清除表单就是修改将表单驱动为所需的“清除”定义的视图模型。在大多数情况下(包括您的情况),只需将视图模型设置为新对象即可:
$scope.submit = function(place) {
$scope.newForm.$setPristine();
$scope.newForm.$setUntouched();
// clear the form
$scope.place = {};
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)