Allenph Allenph - 3 months ago 10
AngularJS Question

Accesing $pristine property of input without form in Angular?

Say I have the following HTML...

<div class="row">
<div class="col-xs-3 align-right">
<p>Email</p>
</div>
<div class="col-xs-7">
<input type="text" class="form-control" ng-model="registrationForm.email.value"/>
<span class="error-label" ng-hide="registrationForm.email.valid"><span class="glyphicon glyphicon-remove"></span>Must be a valid email!</span>
</div>
</div>


This bit of HTML creates an email field, with an error label that is shown if the email provided is invalid. This works perfectly, and is not part of my question.

I would like to slightly alter the behavior of this label. When the user first visits the form, I don't want to display the error label unless the user has changed the value of the form input.

It seems like the
$pristine
and
$dirty
properties are the key, but I'm confused on how to go about using them. If I try to access them of properties of
email.value
(I.E.
registrationForm.email.value.$pristine
) the property seems to be undefined.

I would like to avoid enclosing these inputs in an HTML form. Is there still a way I can retain use of these properties, and if so, how?

Answer

When you create your <form> element, it will create a $scope variable with the name of your form. For example:

<form name="regForm">
  <div class="row">
    <div class="col-xs-3 align-right">
      <p>Email</p>
    </div>
    <div class="col-xs-7">
      <input type="text" class="form-control" name="email" ng-model="registrationForm.email.value"/>
      <span class="error-label" ng-hide="registrationForm.email.valid"><span class="glyphicon glyphicon-remove"></span>Must be a valid email!</span>
    </div>
  </div>
 </form>

You can access the $pristine using $scope.regForm.email.$pristine.

Without a <form>, simply use ng-form, which will give you the functionality of the form, without needing an actual <form> element. See this post for more information.

Comments