Understanding AngularJS Directives

AngularJS is a beautiful framework that comes packed with a fantastic feature called Directives. Directives are one of the most core components of Angular that can be used to manipulate the DOM, perform data binding, associating controllers/scope with a view and much more. Directives can together add to the strength of AngularJS and make it more responsive. Directives are the foundation of Angular and define webmasters how they can interact with it.

Although, AngularJS comes complete with a great deal of directives. Some of them are ng-click, ng-controller, ng-shown/ng-hide, ng-repeat, and more can be easily found in the framework. In this post, we will explore everything related to the AngularJS directives. What are they and how they can be useful for developers in getting started with AngularJS.

First, we will look at the basics of Directives.

What are Directives?

2

At its bare bones, Directives are nothing but a way to expand HTML vocabulary to do some new, smart things. They add a new element or new attributes to the existing elements. They are special markers on the DOM element which add a specific behavior to it. Directives can be run when the DOM is compiled by the compiler.

Using it, AngularJS allows us to define our own directive using which we can simplify the process of manipulating DOM. And, also totally modify the behavior of HTML.

Here is how Angular enables you to use your own directive in HTML.

<div angular></div>

<div class="angular"></div>

<angular></angular>

<!-- directive: angular →

For lengthy names, words can be split by using hyphens at the time of declaration and camel cased it to define the directive.

<div take-this-test-once-again-to-score-well></div> 

App.directive('TakeThisTestOnceAgainToScoreWell', function() {... });

Following are the types of Directives which you can implement:

  • Element directives
  • Attribute directives
  • CSS Class directives
  • Comment directives

Why Directives are Used in AngularJS

A typical HTML file comes with elements such as <span>, <input>, etc. and most of them have fixed behavior properties. If you want the <input> element to exhibit the behavior like datepicker, it needs to take custom CSS and JS calls from the JavaScript. Angular JS makes this process absolutely easy as it allows us to wrap all this in a specific directive. So instead of writing:

<input id="datepickerElem">

and calling,

$('#datepickerElem').datepicker()

You can simply write, directly in your HTML

<input datepicker>

or

<datepicker>

This Is How a Basic Directive Looks and Works

myapp = angular.module("myapp", []);

myapp.directive('div', function() {

    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */

    directive.template = "My first directive: {{textToInsert}}"; 

    return directive;

});

Here, we have first registered a directive with a module and then have called the directive () function on the module.  While calling this function, a new directive can be registered. The first parameter to the ‘directive’ function should be the name of the directive itself. This is the name which you can use in your HTML template while activating the directive. Here, I have used the name ‘div’. This implies that the directive will get activated as soon as an HTML element with the name ‘div’ is found within the template.

Now, look at the second parameter that has been passed to the ‘directive’ function. This is known as factory function. The primary objective of this function is to return a directive whenever it’s being called. AngularJS calls this function to obtain JavaScript object, consisting the definition of the targeted directive. Observing closely the above  mentioned code, you’ll notice how the function has returned the JavaScript object.

There are mainly two properties provided by the returned JavaScript function. They are:

  • Restrict field
  • Template field

The ‘restrict’ field is used if any directive needs to be activated by matching either the HTML element or its attribute. Once the ‘restrict’ property has been set to E, you can easily define that only HTML element with the name ‘div’ should activate the directive. Further, setting the same property to A, you can define that only HTML element named ‘div’ should activate the directive. Additionally, combining the value AE, you can define both HTML element names as well as their attribute names.

Now, let’s talk about the ‘template’ field. The ‘template’ field is basically a kind of an HTML markup that will be generated after compiling and associating the directive with the Angular. This isn’t a simple string, it could be complex and most often includes some other directives, expressions ( { { } } ). In fact, there are some cases wherein templateUR1 is used instead of template. So, it makes more sense to place the template in an individual HTML file while referencing it to the templateUR1.

You can either create a square file or wrap it in the <script> tags. This is how you can go about it.

<script type='text/ng-template' id='whoiam.html'></script>

To make the process successful, it is recommended to set the Type accurately, otherwise Angular will start looking for the file on your file system.

The following example will clear the point:

<script type='text/ng-template' id='whoiam.html'>

    <div class="thumbnail" style="width: 260px;">

      <div><img ng-src="{{data.owner.avatar_url}}" style="width:100%;"/></div>

      <div class="caption">

        <p><b>Name: </b>{{data.name}}</p>

        <p><b>Homepage: </b>{{data.homepage}}</p>

        <p><b>Watchers: </b>{{data.watchers}}</p>

        <p><b>Forks: </b>{{data.network_count}}</p>

      </div>

    </div>

 </script>

Let’s Wrap Up

This completes our basic understanding of AngularJS directives. I hope this post will be useful for those who are getting started with AngularJS. Reading it thoroughly will allow you follow the best practices of making the most out of these directives.

Maria Mincey is an software developer for Xicom Technologies, a PHP web development company which delivers most comprehensive web applications and solutions for different industry verticals.

Be first to comment