angularjs logo

AngularJS Custom Directives – Basics

One of the many good features of AngularJS is that you can create your own directives, the custom directives.

Types of Custom Directives in AngularJS

You can create four types of custom directives in AngularJS.

  1. Element directive
  2. Attribute directive
  3. Class directive
  4. Comment directive


Element directive, <player></player>

Attribute directive, <span player></span>

Class directive, <span class=”player”></span>

Comment directive, <!– directive:player –>

Creating a Basic Custom Directive

This is how we can register our directive

  1. What we have done is simply registered an Element type directive with its name as the player. Whenever any HTML element ‘player’ is found in our AngularJS application, this custom directive ‘player’ will come into play.
  2. If you want to register the directive as Attribute type, simply replace ‘E’ by ‘A’ in the above code.
  3. And if you want to use both types for this directive, use ‘EA’ instead.
  4. The value of directive.template is what will be shown on the webpage.

Lets’ use this directive. As we have registered this custom directive as element type so we only need to use HTML player tag.

Wherever this tag is placed, it will display “This is my custom directive” and if it was an attribute type directive, then we had to do following

Right now template.directive is simple by having only a sentence. What if we have to display relatively longer part of a template containing HTML? The answer is simple, we will use directive.templatURL instead and will give it the path of that file.

Now AngularJS will load the directive-template.html file.

Still there is a lot more about custom directives which will be discussed in coming articles. This is enough for now to understand the basics of AngularJS custom directives.