27.03.2017 Views

ng-book

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Filters 49<br />

formName.inputfieldName.$error<br />

If a validation fails, then this property will be true; if it is false, then the value has passed the input<br />

field.<br />

A Little Style Never Hurts<br />

When A<strong>ng</strong>ularJS is handli<strong>ng</strong> a form, it adds specific classes to the form based upon the current state<br />

of the form (i.e. if it’s currently valid, uncha<strong>ng</strong>ed, etc.). These classes are named similarly to the<br />

properties that we can check, as well.<br />

These classes are:<br />

.<strong>ng</strong>-pristine {}<br />

.<strong>ng</strong>-dirty {}<br />

.<strong>ng</strong>-valid {}<br />

.<strong>ng</strong>-invalid {}<br />

They correspond to their counterpart on the particular input field.<br />

When a field is invalid, the .<strong>ng</strong>-invalid class will be applied to the field. This particular site sets<br />

the CSS class as:<br />

input.<strong>ng</strong>-invalid {<br />

border: 1px solid red;<br />

}<br />

input.<strong>ng</strong>-valid {<br />

border: 1px solid green;<br />

}<br />

$parsers<br />

When our user interacts with the controller and the $setViewValue() method has been called on<br />

the <strong>ng</strong>ModelController, the array of $parsers functions are called as a pipeline. The first $parser<br />

is called and passes its value to the next, and so on and so forth.<br />

These functions have the opportunity to convert the value and cha<strong>ng</strong>e the validity state of the control<br />

by usi<strong>ng</strong> the $setValidity() functions.<br />

Usi<strong>ng</strong> the $parsers array is one way we can create a custom validation. For instance, let’s say we<br />

want to confirm a value is between two numbers. We’ll push a new function on the $parsers array<br />

that is called in the validation chain.<br />

The value that we return from this $parser function is the value that will be passed down the chain<br />

to the next parser. We return undefined if we don’t want the model to update.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!