김영민
김영민

Reputation: 13

Why the ng-pristine class in AngularJS form always returns true

Why the ng-pristine class in AngularJS form always returns true.

enter a value in the input field and click the button, it does not return false, it returns true.

test.html

<div ng-app="myModule">
  <div ng-controller="myController">
    <form name="myForm" ng-submit="su()">
      <input name="input1" type="text">

      <button id="button1" type="submit" >>>>>></button>
    </form>
    
    myForm.$pristine : {{results}}
    
  </div>
</div>

test.js

var module = angular.module("myModule", []);

module.controller("myController", function($scope) {
    $scope.su = su;
    $scope.results = "default";
    function su()
    {
        $scope.results = $scope.myForm.$pristine;
    }
});

Upvotes: 1

Views: 46

Answers (1)

Naren Murali
Naren Murali

Reputation: 57442

We need to add the ng-model attribute to the form elements, so that pristine and dirty are updated, after this it's working fine.

Pristine is defined as below

ng-pristine:

The ng-pristine class tells that the form has not been modified by the user. This returns true if the form has not been modified by the user. Return type: Return Boolean True if the form/input field is not modified by the user else it returns False.

Pristine dirty article

Working example below:

var module = angular.module("myModule", []);

module.controller("myController", function($scope) {
    $scope.su = su;
    $scope.results = "default";
    function su()
    {
        $scope.results = $scope.myForm.$pristine;
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="myModule">
  <div ng-controller="myController">
    <form name="myForm" ng-submit="su()">
      <input name="input1" type="text" ng-model="input1">
        <div class="info" ng-show="myForm.input1.$pristine"> 
            Now Pristine 
        </div> 
        <div class="error" ng-show="myForm.input1.$dirty"> 
            Now Dirty 
        </div> 
      <button id="button1" type="submit" >>>>>></button>
    </form>
    
    myForm.$pristine : {{myForm.$pristine}}
    
  </div>
</div>

Upvotes: 0

Related Questions