Trifork Blog

Angular Directives, a beginners guide - part 1

April 17th, 2014 by
| Reply

What are directives?

AngularJS-largeTo start with Angular Directives we must first know what Google's Angular team defines as directives, so I copied a little piece form their website and I'll comment on that.

"At a high level, directives are markers on a DOM element (such as an attribute, element name, or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children."

So....in plain English this means you can create your own HTML(DOM) elements or add specific attributes with their own data, behaviour and design.
To give you an idea of what the different types of directives are and look like, I've set up some example code which you can download (here) or you could look at the codepen examples on this page.

Attribute

The attribute directive is actually nothing more then the ability to add a custom attribute to a new or already existing HTML element.

Creating a directive with only attribute information will not limit you in any way to add your HTML elements or add behaviour. I have to add that it is wise to add your own prefix to prevent overriding current or new native HTML attributes. You could add new functionality by adding a empty attribute to a INPUT tag, so it will for example automatically open a date picker on focus. Maybe you want to really specify new functionality by giving the directive some information, so then you would actually fill your newly created attribute with a certain value.

One of the most basic directive examples is the attribute directive without a value. With this example you add the custom attribute to any HTML(DOM) element and Angular will execute it as shown in the example.

To make things a little more dynamic and interesting we will now look at the attribute directive with a value. In the following example the parameters are passed through to the Angular directive.

Element

The element directive clearly gives you the idea that you're creating a new type of HTML element with its own behaviour and looks.

Codewise the element directive doesn't differ that much from the attribute directive except for targeting the content between your newly created tag.

Choose your approach

So now (with the examples) we've seen the attribute directive (with and without attribute values) and the element directive. There are no rules set when to use a specific approach, but if you think about it, it would make sence that an attribute approach would enhance an already existing element and the element approach would/should bring something totally new, that doesn't already exist within the current HTML spec.

Next time

On my next post I will go into the other directives 'class' and 'comment', why you would choose to use them. Also I'll create some example where directives enhance/add (new) behaviour.

Leave a Reply