Beginning AngularJS

(WallPaper) #1
CHApTer 5 ■ DIreCTIveS

For a relatively small amount of code, we get a fairly useful piece of functionality. This shows how directives can
be greater than the sum of their parts. It also shows, I hope, that directives can lead to well-encapsulated code that can
keep complexity out of sight. We can do even better still, but we will get to that when I cover custom directives in the
last section of this chapter.


Built-in Directives


In this section, we will take a look at a few very useful built-in directives. We can’t look at all of them here, as it would
take far too long. However, I would like to give you a sense of the directives that ship with the framework and some
examples of how they work. I won’t pay much attention to HTML form-related directives, as these get their own
coverage in the next chapter.


ngBind

Much of the time, you don’t use ngBind directly, because the double curly braces achieve the same thing. For
example, the following two code snippets are functionally equivalent:



{{2+2}}


Both ngBind and the expression syntax ask Angular JS to display the value of a given expression and update the
output accordingly when the value of that expression changes.
If we have expressions, why bother to use ngBind? A benefit of using the ngBind approach relates to the fact that,
if a document takes some time to load, your HTML page might temporarily show the raw expressions to your end
users. That is to say, they may literally see the {{2+2}} appear momentarily before Angular JS gets a chance to compile
it and show the desired values. Using ngBind does not have this unfortunate side effect.
You probably don’t want to give up using the curly brace syntax, so keep reading. The ngCloak directive is here to
save the day.


ngCloak

If your document is taking time to load, and you are noticing issues with the raw expressions that are appearing, you
don’t have to use the ngBind approach mentioned previously. You can use ngCloak instead. This directive is shown in
action following:


{{ 2 + 2 }}


Here we “cloak” the Angular expression simply by declaring ngCloak (no value is required for this attribute). The
cloaking of the expression happens because ngCloak applies a CSS rule that hides it, although it is only hidden until
Angular JS has determined that it can display the evaluated value.
It is tempting simply to add this directive to the body element, so that it applies to the whole document hierarchy,
but often this is not a good idea. This would prevent the browser’s natural desire to render the page progressively.
Instead, it is often better to apply it on individual elements. Better yet, if your document is not large enough to be
exhibiting this undesirable behavior, don’t use it at all!

Free download pdf