CHApTer 5 ■ DIreCTIveS
As you can see, it’s quite easy to use this directive. It looks and behaves in the same way as product-detail.
html. It houses a button that is used to show and hide the available colors, but rather than hard-code the colors using
manually crafted div elements, as we did earlier, we will make this directive much more reusable, by using
a colors attribute. This allows us to pass in an array of colors, so that we can determine which colors to use on a
case-by-case basis.
Like filters and controllers, directives are configured on a module. Let’s examine how this works (see Listing 5-7).
It should look relatively familiar.
Listing 5-7. Configuring a Directive
myAppModule.directive('colorList', function () {
return {
restrict: 'AE',
template:
"
- "{{isHidden? 'Show Available Colors' : 'Hide Available Colors'}}"
- """
- "
}
});
We’ll build on this until our directive is fully implemented, but for now, let’s focus on what is achieved in
Listing 5-7. Using the directive method on the module, we have registered a directive with the Angular JS framework.
We named this directive, via the first argument, colorList. The second argument is an anonymous function, which
returns a directive definition object. This is a regular JavaScript object that we need to set up with various properties
that tell Angular JS all about our directive. So far, all that we have configured is the restrict and template options.
Let’s deal with restrict first.
The restrict Option
The restrict option is used to specify how a directive can be invoked. As you saw earlier, there are four different ways
to invoke a directive. This corresponds to the four valid options for restrict.
Table 5-3 provides an example of each valid option. As our directive uses the value 'AE'; this means that it can be
invoked as either an attribute or an element. As I mentioned earlier in this chapter, you won’t use the last two options,
C and M, as they exist mainly for use with much older browsers.
Table 5-3. Valid restrict Options
Option Example
A
E
C
M