Introduction to Directives
As web developers, we’re all familiar with HTML. Let’s take a moment to review and synchronize our terminology around this most fundamental of web technologies.
HTML Document
An HTML document is a plain text document that contains structure and may be styled through CSS or manipulated with JavaScript.
HTML Node
An HTML node is an element or chunk of text nested inside another element. All elements are also nodes; however, a text node is not an element.
HTML Element
An element comprises an opening tag and a closing tag.
HTML Tag
An HTML tag is responsible for marking the beginning and end of an element. A tag itself is declared using angle brackets.
An opening tag contains a name that becomes the name of the element. It can also contain attributes, which decorate the element.
Attributes
To provide additional information about an element, HTML elements can contain attributes. These attributes are always set in the opening tag. We can set them in a key-value pair, like key="value"
, or as only a key.
Let’s take a look at the <a>
hyperlink tag, which is used to create a link from one page to another:
Some tags, like the hyperlink tag, have special attributes that act much like arguments to the tag. For example, the href
attribute of a link tag enables the behavior of the link tag and also turns the text node in between the opening and closing tags blue by default on all browsers.
<a href="http://google.com">
Click me to go to Google</a>
The <a>
tag defines a link between another page on our site or off our site, depending on the contents of the href
attribute, which defines the link’s destination.
It is noticeably different from the following HTML element, the button:
<button href="http://google.com"
type="submit">Click me</button>
The link tag is, by default, underlined and blue, while the button, by default, looks like a clickable button in our browser.
The link tag knows that, when provided an href
attribute that points to http://google.com
, it should change the URL in the address bar and load Google’s home page when a user clicks on the link.
The button tag, on the other hand, is completely oblivious when provided an href
attribute and does not perform the same behavior (the attribute is ignored).
Thus, changing the URL in the address bar and bringing you to a new page is part of a link’s pre-programmed behavior, but not part of a button’s pre-programmed behavior.
Finally, both tags perform the same behavior when provided a title attribute: They provide a tooltip to the user upon hover.
<a href="http://google.com"
title="click me">
Click me to go to Google
</a>
<button type="submit"
title="click me">Click me</button>
In summary, the web browser renders our HTML elements’ style and behavior; this capability is one of the fundamental strengths of the web.
Each vendor, whether it be Google or Microsoft, tries to adhere to the same HTML spec, therefore making programming for the web consistent across devices and operating systems.
Past versions of Internet Explorer have not complied with the common HTML spec, so we need to perform some tricks to get older versions of IE to work. See the Internet Explorer chapter for more details.
Recently, new HTML tags have begun to emerge. These are a part of the HTML5 spec. For example, the video tag, which specifies a video, movie clip, or streaming video:
<video href="/goofy-video.mp4"></video>
These new HTML5 tags work on on newer browsers and are generally not supported by Internet Explorer version 8 and lower.
Directives: Custom HTML Elements and Attributes
Given what we know about HTML elements, directives are Angular’s method of creating new HTML elements that have their own custom functionality. For instance, we can create our own custom element that implements the video tag and works across all browsers:
<my-better-video my-href="/goofy-video.mp4">
Can even take text</my-better-video>
Notice that our custom element has custom open and closing tags, my-better-video
, and a custom attribute, my-href
.
To make our tag more usable, we could just override the browser-provided video
tag, which means we could instead use:
<video my-href="/goofy-video.mp">
Can still take children nodes
</video>
As we can see, directives can be combined with other directives and attributes; this combination is called composition.
To effectively understand how to compose a system from smaller parts, we must first understand the primitive pieces. Facilitating that understanding will be the underlying goal of the next few chapters. Let’s get started.
Bootstrapped HTML
When the browser loads our HTML page along with Angular, we only need one snippet of code to boot our Angular application (we learned about it in the introductory chapter).
In our HTML we need to mark up the root of our app using the built in directive ng-app
. This directive is meant to be used as an attribute; thus, we could stick it anywhere, but let’s choose the opening <html>
tag, which is normative:
A built-in directive is one that ships out of the box with Angular. All built-in directives are prefixed with the ng
namespace. In order to avoid namespace collisions, do not prefix the name of your own directives with ng
.
<html ng-app="myApp">
<!-- $rootScope of our application -->
</html>
Inside of our <html>
element, we can now use any of the built-in or custom directives we want. Furthermore, all of the directives we use within this root element will have access to $rootScope
as a result of the prototypical inheritance in our JavaScript code if the method of the directive has access to scope. Access to scope, in this case, means that scope has been linked to the DOM, which is done late in the directive lifecycle.
Because the life cycle of a directive is sufficiently complex, it warrants its own section. In that section, we’ll also discuss which methods within a directive have access to scope and how scope is shared between one directive and the next. See the directives explained chapter for more information.
Our First Directive
The quickest way to get our feet wet is to just dive right in. Let’s go ahead and create a very basic custom directive. Consider the following HTML element, which we’ll define in a moment:
<my-directive></my-directive>
Provided we’ve created an HTML document and included Angular as well as the ng-app
directive in the DOM to mark the root of our app, when Angular compiles our HTML, it will invoke this directive.
Invoking a directive means to run the associated JavaScript that sits behind our directive, which we define using a directive definition.
The myDirective
directive definition looks like:
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
template: '<a href="http://google.com">
Click me to go to Google</a>'
}
});
The above JavaScript is called a directive definition. We’ll see all the options for defining a directive in directive definition.

With the .directive()
method, provided by the Angular module API, we can register new directives by providing a name as a string and function. The name of the directive should always be camelCased, and the function we provide should return an object.
Camel casing words is the practice of writing compound words or phrases without spaces such that each word, usually with the exception of the first word, begins with a capital letter, and the phrase becomes a single word. For instance: bumpy roads
in camel case notation would be bumpyRoads
.
In our case, we declare the directive in HTML using my-directive
, the directive definition must be myDirective
.
The object that we return from the .directive()
method comprises methods and properties that we use to define and configure our directive.
In an attempt to master the simplest directive possible, we’ve only defined our directive with two options: restrict
and template
.
In directives explained, we’ll cover all of the available methods and properties we can use when defining our own directives, but for the moment, let’s check out the input HTML as compared to the output HTML by using Google Chrome and its developer tools.
First, open up your HTML document using Chrome. You’ll see a blue link that says “Click here”. Take a look at the source code by going to View > Developer > View Source
. You should see the following picture:
Ready to master AngularJS?
- What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall? Imagine how quickly you could work if you knew the best practices and the best tools?
- Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
- You will learn what you need to know to work professionally with ng-book: The Complete Book on AngularJS or get your money back.
Get it now