The Directive API is one of the coolest features of angularjs. Now that you’ve been developing in angularjs for some time, you’ve come across many simple directives, such as ng-repeat, ng-show, ng-model, etc. But when you come to develop real world apps you’ll most likely need custom directives. This chapter will teach you how to build these and implement them in our demo app.

What Are Directives, Really?

A directive is something that attaches special behavior to a DOM element and teaches it awesome tricks! Let’s take the example of the built-in ng-repeat directive: What this does is attach special behavior to a DOM element by repeating it multiple times. Similarly, ng-show and ng-hide conditionally show or hide an element. Let’s think of a few scenarios in which directives could help solve a problem. For example, normal HTML markup can’t create a date picker widget. To introduce a custom element like this into HTML you need a directive. In essence, the basic idea behind directives is quite simple: to help to make your HTML truly interactive by attaching event listeners to the elements and/or transforming the DOM.

Directives From the jQuery Perspective

Let’s imagine how we attach special behaviors to elements in jQuery. To implement a date picker, first we create a normal HTML input element, like this:

<input type="text" class="date-picker"/>

Then we change its default behavior through some JavaScript code, which might look something like this:


But when other designers see your code they might not immediately see what this element does. They need to check out the underlying JavaScript code to be sure of its function. But with angularjs you can create a directive for this element and use it like this:


In this way, you can create truly reusable components with directives, and this approach to building custom components is definitely neater and more intuitive.