我在angular中有一个重置函数来清除表单中的所有字段。如果我这样做:
<a href="#" ng-click="resetForm()">reset</a>
$scope.resetForm = function() {
$scope.someForm = {};
}一切都很好。但是我想在网站上的多个表单中使用这个函数。如果我像这样传递表单对象:
<a href="#" ng-click="resetForm(someForm)">reset</a>
$scope.resetForm = function(form) {
$scope.form = {};
}那它就不会起作用。有人能给我解释一下为什么会发生这种情况吗?
发布于 2014-01-01 11:08:20
你有两个问题:
someForm。form = {}时,它也不起作用,因为它只更改了参数的引用,而不是传递给的引用尝试:
$scope.resetForm = function(form) {
//Even when you use form = {} it does not work
form.fieldA = null;
form.fieldB = null;
///more fields
}或
$scope.resetForm = function(form) {
//Even when you use form = {} it does not work
angular.copy({},form);
}而不是:
$scope.resetForm = function(form) {
$scope.form = {};
}在你的演讲中,我看到你并没有将视图与模型分开。这样做是为了分离关注点,并避免在清除所有字段(包括DOM表单对象的字段)时可能发生的问题。
<form name="form2" ng-controller="SecondController">
<label for="first_field">First Field</label>
<input ng-model="form2Model.first_field" />
<br />
<label for="second_field">Second Field</label>
<input ng-model="form2Model.second_field" />
<br />
<a href="#" ng-click="secondReset(form2Model)">Reset the form</a>
</form>http://plnkr.co/edit/x4JAeXra1bP4cQjIBld0?p=preview
发布于 2017-06-24 00:50:07
您还可以执行以下操作:
form.fieldA = undefined; 它适用于单选按钮和复选框。
发布于 2018-03-29 17:59:34
你可以尝试这样做:在表单按钮重置中部署你的函数,用这种方式...
<input type ="button" ng-click="Object.field1 = null; ObjectN.fieldN = null;" value="Reset" />https://stackoverflow.com/questions/20865125
复制相似问题