Angularjs形式复位 [英] Angularjs form reset

查看:149
本文介绍了Angularjs形式复位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在角复位功能,清除表单中的所有字段。如果我是这样的:

I have a reset function in angular to clear all the fields in a form. If I do something like:

<a href="#" ng-click="resetForm()">reset</a>

$scope.resetForm = function() {
  $scope.someForm = {};
}

一切工作正常。但我想使用此功能在网站上多种形式。如果我通过表单对象,如:

Everything works fine. But I want to use this function for multiple forms on the site. If I pass the form object in like:

<a href="#" ng-click="resetForm(someForm)">reset</a>

$scope.resetForm = function(form) {
  $scope.form = {};
}

然后,它不会起作用。谁能给我解释一下为什么会是这样吗?

Then it won't work. Can someone explain to me why this would be happening?

推荐答案

您有2个问题:


  • 您不是在访问变量传递的,仍然可以访问的电流范围 someForm

  • 当你传递参数的功能,它是按引用传递。即使您使用表= {} ,这是行不通的,因为它只能改变参数的参考,而不是在通过参考 someForm

  • You're not accessing the passed in variable, still access the someForm of current scope.
  • When you pass parameter to the function, it's passed by reference. Even when you use form = {}, it does not work because it only changes the reference of the parameter, not the reference of the passed in 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表单对象的字段)。

In your plunk, I see that you're not separating the view from the model. You should do it for separation of concerns and to avoid problems that might happen when you clear all the fields (including DOM form object's fields).

<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>

<一个href=\"http://plnkr.co/edit/x4JAeXra1bP4cQjIBld0?p=$p$pview\">http://plnkr.co/edit/x4JAeXra1bP4cQjIBld0?p=$p$pview

这篇关于Angularjs形式复位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆