AngularJS: How to name directives

Ciro Nunes
2 min readSep 21, 2014

Quick tips to avoid issues with custom directive names

AngularJS directives allow us to use our own vocabulary to create semantic HTML components. To take advantage of that we should be aware of how it works to avoid some annoying and hard to find issues.

Differences between defining and using

Before start digging into the best practices, let's understand the fundamentals. Let's see how to define and then, how to use an directive.

Defining (the JS)

To define a new custom directives all we need to do is use the directive method which expects two parameters: a name and a constructor function.

angular.module('myDirectives', []).
directive('myAwesomeDirective', function() {
return {
restrict: 'E',
template: '<h1>This is awesome!</h1>'
};
});

In this case, the name must be written using camelCase and each capital letter will represent a dash when we use this directive.

Using (the HTML)

<my-awesome-directive></my-awesome-directive>

In this case, the name must be written using dashes and each dash represents a capital letter from the directive definition.

The $compile converts from camelCase to dash-separated behind the scenes. So, make sure you use the names correctly otherwise it won't work.

Use an unique preffix

I see a lot of times people starting with Angular, which by instinct name their directives with one word like: <dialog> or <tabs>. The reason why this is not a good ideia is because we can have new HTML elements in the future (HTML6?) named exactly with the same name of our custom directive. BTW this is the case of the <dialog> element.

To avoid naming collision with future HTML elements, use a preffix as a kind of namespace

A recommended and wide spread convention from the Angular community is to have two letters preffix names that identifies your application or library.

Examples:

  • ng- (from the core)
  • ui- (from angular-ui)
  • my- (common in examples)
  • wm- (Wealth Management project)

Make sure to also avoid the "ng-" which is used for AngularJS core directives.

Conclusion

TLDR;

Use camelCase in the JS and dash-separated in the HTML as expected by the AngularJS compiler. Choose an unique two letters preffix for your directives and avoid the "ng-" preffix. Have fun!

--

--

Ciro Nunes

πŸ‘¨β€πŸ‘©β€πŸ‘§, πŸ‡§πŸ‡·, πŸ‡¦πŸ‡Ί, ⚽️, web development, js, functional programming, haskell, ocaml, reasonml, rust, entrepreneurship, martial arts