Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


We end up with this kind of HTML repeated all over our forms:


<div class="control-group" ng-class="{'error' : form.email.$invalid
&& form.email.$dirty, 'success' : form.email.$valid && form.
email.$dirty}">
<label for="email">E-mail</label>
<div class="controls">
<input type="email" id="email" name="email" ng-model="user.email"
required>
<span ng-show="form.email.$error['required'] && form.email.dirty"
class="help-inline">Email is required</span>
<span ng-show=" form.email.$error['email'] && form.email.dirty"
class="help-inline">Please enter a valid email</span>
</div>
</div>

We can eliminate much of this duplication by creating a field directive. The
directive will insert a suitable template containing a labeled input control. Here is an
example of using the field directive:


<field type="email" ng-model="user.email" required >
<label>Email</label>
<validator key="required">$fieldLabel is required</validator>
<validator key="email">Please enter a valid email</validator>
</field>

Now we simply provide ng-model, type, and validation directives for the input, as
attributes on the field. Then we provide the label and validation messages as child
elements of the field element. Note, also that we can use a $fieldLabel property
inside the validation messages. This property will be added to the scope of the
validation messages by the field directive.


The field directive has a number of requirements that are hard to achieve with the
built-in directive API.



  • Rather than specifying a single template for the whole directive, we need
    to insert a different template depending upon the type of field that is being
    displayed. We cannot use the template (or templateUrl) property on the
    directive definition object.

  • We need to generate and apply unique name and id attributes for the input
    and wire up the label elements for attribute, before the ng-model directive
    is compiled.

  • We want to extract the validation messages for the field from the child
    validator elements to be used in the template when there is an error with the
    field's value.

Free download pdf