【问题标题】:Angularjs form resetAngularjs表单重置
【发布时间】:2014-01-18 20:22:25
【问题描述】:

我有一个角度重置功能来清除表单中的所有字段。如果我这样做:

<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 = {};
}

那就不行了。有人可以向我解释为什么会这样吗?

【问题讨论】:

标签: javascript forms angularjs


【解决方案1】:

你有两个问题:

  • 你没有访问传入的变量,仍然访问当前作用域的someForm
  • 当您将参数传递给函数时,它是通过引用传递的。即使您使用form = {},它也不起作用,因为它只更改参数的引用,而不是传入的someForm 的引用。

试试:

$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

【讨论】:

  • 感谢您的建议。可悲的是,它似乎也不起作用。此外,如果我在表单上执行 console.log,它会显示它正在调用两次重置函数。我不确定它为什么会这样做。
  • @sturoid:使用当前代码,我不知道为什么它会调用resetForm 两次,也许问题出在其他地方。
  • 谢谢你说得有道理。问题是,如果我将它与多个表单一起使用,那么我将不得不考虑表单传递的所有字段。是否可以对每个字段进行循环并将它们设置为 null 或类似的东西?
  • @sturoid:是的,这也是一个解决方案。我只是指出了您无法重置表单的问题。
  • @sturoid:我看到你从来没有接受过答案。请这样做,以便人们知道哪种解决方案可以解决问题中的问题。
【解决方案2】:

你也可以这样做:

form.fieldA = undefined; 

它非常适合单选按钮和复选框。

【讨论】:

    【解决方案3】:

    你可以试试这个: 以这种方式在表单按钮重置中部署您的功能...

    <input type ="button" ng-click="Object.field1 = null; ObjectN.fieldN = null;"  value="Reset" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多