Beginning AngularJS

(WallPaper) #1
CHApTer 5 ■ DIreCTIveS

I wish I could say that all of the answers are to be found in the API documentation, but many of the problems that
I see posted in online forums are indeed readily available here. If you run into problems, or you just want to look up
some more directives, it should certainly be at the top of your list of places to go to find help.


Creating a Custom Directive


While there are plenty of built-in directives, you will occasionally need to build your own application-specific
directives. In this section, we will look at an example that should serve to get you up to speed on the basics of how to
do just that. Custom directives can seem a bit intimidating at first, mainly because there are a lot of moving parts.
My aim here is to get you up to speed with the basics and put you in good shape to tackle the more advanced
aspects as and when you need them. To achieve this, we will create a custom directive that we will call colorList. This
directive will encapsulate much of the code we looked at in Listing 5-1. To recap, this produced a color selection list,
which could be activated and deactivated using a button. Listing 5-6 shows how this directive can be used within the
product-detail.html file.


Listing 5-6. The colorList Directive in Use


<!DOCTYPE html >




A Custom Directive




AngularJS Socks


Keep warm this winter with our 100% wool, 100% cool, AngularJS socks!





Table 5-2. Information Available Through the Online API Documentation


Directive Name and Overview The directive’s name, for example; ngRepeat


Directive Info Additional information, such as the priority level, which may impact
the behavior of the directive


Usage This corresponds to our discussion of how a directive can be used.
For example, some directives can be used only as an attribute.


Arguments This tells you if the argument(s) should be an Angular JS expression,
a string, or some other value.


Example A brief example of the directive in action

Free download pdf