O'Reilly logo

AngularJS by Brad Green, Shyam Seshadri

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Directives

With directives, you can extend HTML to add declarative syntax to do whatever you like. By doing so, you can replace generic <div>s and <span>s with elements and attributes that actually mean something specific to your application. The ones that come with Angular provide basic functionality, but you can create your own to do things specific to your application.

First we’re going to go over the directives API and how it fits within the Angular startup and runtime lifecycles. From there, we’ll use this knowledge to create several classes of directives. We’ll finish the chapter with how to write unit tests for directives and how to make these run quickly.

But first, a few notes on the syntax for using directives.

Directives and HTML Validation

Throughout this book, we’ve used Angular’s built-in directives with the ng-directive-name syntax. Examples include ng-repeat, ng-view, and ng-controller. Here, the ng portion is the namespace for Angular, and the part after the dash is the name for the directive.

While we prefer this syntax for ease of typing, it isn’t valid in many HTML validation schemes. To support these, Angular lets you invoke any directive in several ways. The following syntaxes, laid out in Table 6-1, are all equivalent to allow for your preferred validator to work properly:

Table 6-1. HTML Validation Schemes
ValidatorFormat Example

none

namespace-name

ng-repeat=item in items

XML

namespace:name

ng:repeat=item in items

HTML5

data-namespace-name

data-ng-repeat=item ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required