Beginning AngularJS

(WallPaper) #1
CHApTer 5 ■ DIreCTIveS

When should you use an element and when should you use an attribute? You can use either, and the end
result will be the same. However, the Angular team recommends that you use an element when you are creating a
component that is in control of the template and an attribute when you are decorating an existing element with new
functionality.


The template Option

As the name suggests, the template option lets you define a template. The template is appended to your directive
declaration by default (though there is a replace option that allows you to replace the element on which the directive
occurs entirely). Let’s consider the HTML code that I have provided as the value to the template option. I have shown
this again in Listing 5-8, but, this time, without the string quotations, so it is easier to read.


Listing 5-8. The Value of the template Option




You will recognize the button and the expression within it. The div with the id of colorContainer is new. This
is because we will abandon the approach of hard-coding the color divs manually in favor of dynamically appending
them to this div, based on array values. We will see this in action shortly.


■ Tip I’ve kept things together here for convenience, but there is an additional option for templates in the templateUrl


option. This lets you move the source code for your template into a separate file. This is then loaded via Ajax. For longer


templates, this is usually better than using the template option, as all you have to provide is the UrL to this file.


Of particular note here is that the template contains Angular JS code, such as the ng-click directive and the
expression that renders the button text. Thus, your templates can be as simple or as complex as you need them to be.
With restrict and template covered, we now require a way to tell Angular JS about our underlying logic. This
logic appeared in our controller function earlier, but now we need to encapsulate it within this custom directive. One
way to do this is to use the link option.


The link Option

The function that you assign to the link option is where the main action takes place. This function has access to the
current scope (by default) and the element on which the directive was declared (the div element, in this case). For
clarity, let’s list precisely what we want this directive to achieve. This will make it easier to follow the rationale behind
the implemented logic. The directive should perform the following:



  1. Add a button to the page. This button will be a toggle for showing and hiding a list of
    colors.

  2. By default, the color list should be hidden.

  3. The colors should be shown as div elements that can display a color and color name,
    based on an array of strings corresponding to that color.

  4. The color list should be an array containing CSS color name values. This should be
    available within the directive.

Free download pdf