Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-touched not working - AngularJS

Form fields not being added ng-touched class, instead remains ng-pristine

This is my form:

<form novalidate class="css-form">

            <div class="form-group clearfix">
                <label class="col-xs-12 col-sm-6 col-md-4">State Code</label>
                <div class="col-xs-12 col-sm-6 col-md-8">
                    <input type="text" class="form-control" ng-maxlength="2" ng-model="ObjectNew.stateCode" required>
                </div>
            </div>
            <div class="clearfix"></div>

            <div class="form-group clearfix">
                <label class="col-xs-12 col-sm-6 col-md-4">Zip</label>
                <div class="col-xs-12 col-sm-6 col-md-8">
                    <input type="text" class="form-control" ng-model="ObjectNew.zip" required>
                </div>
            </div>
            <div class="clearfix"></div>

        </form>

When I see in inspect element, it does show only ng-pristine class on each field, even if i went through both fields and leaves null. It shows ng-invalid too, which is fine.

Have to add the styles actually:

.css-form input.ng-invalid.ng-touched {
    background-color: #FA787E !important;
    }

  .css-form input.ng-valid.ng-touched {
    background-color: #78FA89 !important;
  }
like image 967
Fahad Khan Avatar asked Feb 24 '15 11:02

Fahad Khan


1 Answers

The term pristine and touched are not similar. An input will remain pristine as long as it has not been modified. It is untouched, as long as it didn't loose focus - Angular doc states that ng-touched is applied when "the control has been blurred".

So it is possible for an input to be pristine and touched - just click it, and then click somewhere else without typing anything in.

It is also possible for it to be dirty and untouched - click it, type in some text, but do not click anywhere else.

To see that, and see working ng-touched in action, refer to this jsFiddle.

To make sure it works, use Angular 1.3 as pointed out by @dfsq. Also, use angular-touch which matches your Angular version. The JSFiddle above works correctly.

like image 191
kamituel Avatar answered Oct 13 '22 21:10

kamituel