AngularJS Quizzing: Form features

So far we’ve been able to make a quiz question using several Angular directive: ng-app, ng-controller, and ng-if to give feedback for the correct answer. But I’d like to give more feedback than that, so today we’re going to use the form element to get some validation features that come with Angular.

All of my edits are going to be on the HTML page.

First, I’m going to wrap the question within a form element with the name “myForm”. Once I do that, I have access to a bunch of properties that are described in detail in the AngularJS documentation. There’s two properties I want to look for: $pristine and $dirty.

$pristine and $dirty forms

When you use a form element in AngularJS, you can check to see if the form has been used or not. In our case, the form’s name is myForm. So when I first load the page, myForm.$pristine should be true, and myForm.$dirty should be false. But once I start to edit any input fields within the form, those values should reverse, and the form be $dirty instead of $pristine.

You can watch for these properties for the entire form, or narrow down to individual input fields. In our case, I’ve added a name to the input field: myInput. So when the page is refreshed, myForm.myInput.$pristine should be true.

Why do I need to name the input field?

Why do I need to name the input field myInput? Why can’t I just refer to the model name “input” within myForm? I don’t really know. I think it has to do with how AngularJS creates a new form controller when you use the form element. The $pristine, $dirty and some other properties come with Angular’s form controller, but they won’t appear in the model object.

So just remember, if you’re going to use form validation in AngularJS, you need to add name attributes, even if it seems redundant.

Adding more feedback

Now that’ve added the necessary names for myForm, I can use ng-if to make elements appear based on the input field. The first element prompts the user to enter something, and appears when the field is pristine.

When the field is dirty (meaning it’s been used) and the field doesn’t have the correct answer, another feedback element will appear.

In summary, by using Angular’s built-in form validation, we’re able to give more feedback to the user.


Discover more from AaronTweeton.com

Subscribe to get the latest posts sent to your email.