CHApTer 5 ■ DIreCTIveS
The Basics of Directives
What do directives look like? You are no doubt thinking that you have seen enough in use so far to know the answer
to that question. It may surprise you to learn that directives can take on a few different forms. Let’s pick on the
ngController directive as an example.
As you know, the ngController directive looks like the following:
This is a typical directive declaration, and it is by far the most common way to use directives: that is, as an
attribute. One potential issue with this approach is that the document that contains it will not validate as HTML5-
compliant. If this is a concern to you, or your organization, you can do the following instead:
This is very similar to the approach to which we are accustomed, though here we use the prefix data: before our
directive name. Validators are happy with this, because it uses a standard approach to creating custom data attributes.
In both the preceding cases, we invoke the directive using an attribute, though this is not our only option. All of
the following methods are also technically possible:
As an attribute:
As an element:
As a class:
As a comment:
I say “technically possible,” because directives authors may or may not have enabled their directives to be used in
all possible forms. You will learn more about this when we build a custom directive later in this chapter. In reality, you
won’t use the last two options, as they exist mainly for use with much older browsers, and you will rarely see them in
use in the wild. Still, it’s nice to have options, and at least you won’t be caught unawares if you should stumble upon
any of these.
Using Directives
A directive is rarely an island unto itself. That is to say, directives often need to communicate and interact with the rest
of your application. This is usually done through a scope, as you have seen in previous chapters. Let’s start building a
small part of an application that shows this idea in action.