Search code examples
angularjsangularjs-material

AngularJS v1.5.5 Reset form not working for invalid input fields


I have the code below (or see the fiddle) and I try to reset form and clear all input fields too for each form.

With AngularJS version 1.2.1 is working fine! but in my app I using version 1.5.5 because I have other libraries for separating the nested forms in <md-tab> tags using material framework who need this version.

The problem is when any field it's invalid then reset does not work as expected and these fields remain unchanged instead to be clear.

There is another way to clearing all fields (of nested form) when I click reset button ?

angular.module("main", [])
  .controller("register", function($scope) {
    $scope.data = {
      A: {},
      B: {}
    };

    $scope.reset = function(form) {
      form.$setPristine();
    };

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body ng-app="main">
  <div ng-controller="register" class="form">

    <form name="form" novalidate role="form">

      <div class="form">


        <h1>TAB1 - Form A:</h1>
        <ng-form name="A">
          A1:
          <input type="text" ng-model="data.A.A1" ng-minlength="4" ng-maxlength="15" />A2:
          <input type="text" ng-model="data.A.A2" ng-minlength="4" ng-maxlength="15" />
          <button type="button" ng-disabled="A.$pristine" ng-click="reset(A); data.A=null;">Reset</button>
          <br/>
          <strong>A.$pristine =</strong> {{A.$pristine}}
          <strong>A.$valid =</strong> {{A.$valid}}
        </ng-form>
      </div>
      <br/>
      <br/>

      <div class="form">


        <h1>TAB2 - Form B:</h1>
        <ng-form name="B">
          B1:
          <input type="text" ng-model="data.B.B1" ng-minlength="4" ng-maxlength="15" />B2
          <input type="text" ng-model="data.B.B2" ng-minlength="4" ng-maxlength="15" />

          <button type="button" ng-disabled="B.$pristine" ng-click="reset(B); data.B=null;">Reset</button>
          <br/>
          <strong>B.$pristine =</strong> {{B.$pristine}}
          <strong>B.$valid =</strong> {{B.$valid}}
        </ng-form>
      </div>
    </form>

    <h1>data:</h1>
    <pre>{{data | json}}</pre>

  </div>
</body>


Solution

  • It's because ng-model binds to the A and B objects by reference in $scope.data. If you remove the $scope.data.A = null from your ng-click and reset the object without creating a new one, it works:

    https://jsfiddle.net/utwf604r/15/

    $scope.reset = function (form)
    {
      // don't change the reference to A
      // $scope.data.A = {} wont work!!
        angular.extend($scope.data, {A:{A1:'',A2:''}, B:{B1:'',B2:''}});
        form.$setPristine();
    };