Angularjs form reset

后端 未结 3 1244
名媛妹妹
名媛妹妹 2020-12-16 16:45

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

reset

$         


        
相关标签:
3条回答
  • 2020-12-16 17:16

    you can try this : Deploy your function inside form button reset , in this way ...

    <input type ="button" ng-click="Object.field1 = null; ObjectN.fieldN = null;"  value="Reset" />
    
    0 讨论(0)
  • 2020-12-16 17:18

    You can also do:

    form.fieldA = undefined; 
    

    It works great for radio buttons and checkboxes.

    0 讨论(0)
  • 2020-12-16 17:31

    You have 2 problems:

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

    Try:

    $scope.resetForm = function(form) {
      //Even when you use form = {} it does not work
      form.fieldA = null;
      form.fieldB = null;
      ///more fields
    }
    

    Or

    $scope.resetForm = function(form) {
          //Even when you use form = {} it does not work
          angular.copy({},form);
        }
    

    instead of:

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

    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>
    

    http://plnkr.co/edit/x4JAeXra1bP4cQjIBld0?p=preview

    0 讨论(0)
提交回复
热议问题