Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

input[name='email'].ng-dirty.ng-valid {
color: green;
}


It isn’t readily apparent what these last two CSS rules, the style hooks, accomplish, beyond the fact that they both
set the CSS color property, one to red and the other to green. Figure 6-6 sheds some light on the matter. When the
user begins to type, the input text appears in red, indicating that the e-mail address is not yet valid. Once the e-mail
address is recognized as valid, the text becomes green. Figure 6-6 shows how this looks in both states.


Figure 6-6. E-mail input, with visual real-time validation feedback


What is particularly interesting about this feature is that it only requires the addition of some very basic CSS.
As indicated earlier, AngularJS will dynamically add CSS classes as the form changes from one state to another. In this
case, when the page first loads, the e-mail input element has a few classes set on it. One of them is the ngValid class.
Here is how this particular input is enhanced by AngularJS upon page load:


<input type="email" placeholder="Email" name="email" ng-model="person.email" required=""
class="ng-pristine ng-invalid ng-invalid-required ng-valid-email">


Pay special attention to the two bolded classes, ng-pristine and ng-invalid. The former was added because
this input has not yet been touched; it is in pristine condition. The latter was added because the field is currently
invalid. Once the user starts typing his or her e-mail address, AngularJS will update this list of classes on the fly.
At the very first keystroke, the input is no longer pristine. As the following code snippet shows, it is now dirty.


<input type="email" placeholder="Email" name="email" ng-model="person.email" required=""
class="ng-dirty ng-invalid ng-invalid-required ng-valid-email">


At this point, our input[name='email'].ng-dirty.ng-invalid rule kicks in, and the text becomes red. It remains
red until such time as the e-mail address becomes valid. When it does become valid, the list of CSS classes is again
revised by AngularJS.


<input type="email" placeholder="Email" name="email" ng-model="person.email" required=""
class="ng-dirty ng-valid-required ng-valid ng-valid-email">

Free download pdf