Friday, November 22, 2013

Flexible directive names in AngularJS

AngularJS is an HTML compiler. Because of this the most powerful component in Angular is the directive.

The first thing I noticed when using directives in Angular was how they were made available to the application. To use a directive they have to be named and added to a module under that name. You can then use that name to call the directive. When using a directive you usually want to pass in some information to be used. This can be done by setting the directive name as an attribute on the element and then passing an expression to it. This means you have code like the following:

<div my-directive="myExpression" />

So all I need to do is parse the expression and I have my information. This leads to directive code like the following:

I've hard coded in 'myDirective', but what happens if that directive wants to be used under another name? Well the easy fix is to attach that directive to a module and enforce the name of the directive like so:

This is how a directive is registered and where a name is passed in. You can also see this line:

directive.name = directive.name || name;

Which basically says that if no name is provided on the directive object (the object we return from the directive factory) then we set it to the one it is registered with. This means that if we keep a reference to that object then we can use that name variable like so: