Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

Both of the conditional statements in the register() method work the same way; they each check to see if these
fields are not currently valid. If indeed they are not, then the firstNameInvalid and lastNameInvalid variables are
set to true. This will cause the ngShow directive to show the validation error messages.
Moving along to the e-mail address input, the requirement is also that the field is required. In this case, it must
also be a value that is a properly formatted e-mail address. This is easy enough to achieve using the HTML5-based
approach. Study the following input element, which will achieve this:



■ Note As we did before, we again use the required attribute. In this case, we also make use of one of the HTML5-


based input types and specify email as the input type. This means that only properly formatted e-mail


addresses will be considered valid. As you will see shortly, we can take exactly the same approach as we did with the


First name and Last name fields and use the ngShow directive to show and hide the associated validation error


message. The same applies to the research questions’ select element.


■ Caution I am often careful to say “properly formatted -mail address,” as opposed to saying “valid e-mail address.”


The two are quite different things. The string [email protected] is formatted as an e-mail address, but it’s not a valid e-mail ad-


dress!


Let’s use two more form-level properties that we touched on in Table 6-2. While this is a slightly contrived
example, it does show off the use $pristine and $dirty.
At the top of our form, we will place two div elements; both of which use an ngShow directive. The $dirty
property tells us if there has been some interaction with the form. It is true if at least some data has been entered.
The $pristine property is the opposite. It tells us if there has been no interaction with the form. Only one of these div
elements will be visible at any given time; that is, a form cannot possibly be in both states.


Form input has not yet started

Form input has started

Next, we will add a div element underneath our form. This div element contains the “Thank you” message that
we want users to see once they have successfully completed the form. It, too, uses an ngShow directive. In this case,
we rely on the value of the doShow variable, a variable that we set within the register() method of our controller, to
determine whether or not to show the “Thank you” message.



Thank you for taking the time to register!

I will show the complete code listing soon. Just one more thing that we should address before we finish up. At the
moment, the form doesn’t look too good. As Figure 6-4 shows, it’s looking a little cramped and not very presentable.
We will turn it into something a little better, as shown in Figure 6-5.

Free download pdf