1. Code
  2. JavaScript
  3. Angular

Mastering AngularJS Directives

Scroll to top

Directives are one of the most powerful components of AngularJS, helping you extend basic HTML elements/attributes and create reusable and testable code. In this tutorial, I will show you how to use AngularJS directives with real-life best practices. 

What I mean here by directives is mostly custom directives during the tutorial. I will not try to teach you how to use built-in directives like ng-repeat, ng-show, etc. I will show you how to use custom directives to create your own components. 

Outline

  1. Simple Directives
  2. Directive Restrictions
  3. Isolated Scope
  4. Directive Scopes
  5. Directive Inheritance
  6. Directive Debugging
  7. Directive Unit Testing
  8. Directive Scope Testing
  9. Conclusion

1. Simple Directives

Let say that you have an eCommerce application about books and you are displaying specific book detail in several areas, such as the comments, user profile pages, articles, etc. Your book detail widget may be like below:

Book WidgetBook WidgetBook Widget

In this widget there is a book image, title, description, comments, and rating. Collecting that information and putting in a specific dom element may be hard to do in every place you want to use it. Let's widgetize this view by using an AngularJS directive. 

1
angular.module('masteringAngularJsDirectives', [])
2
.directive('book', function() {
3
    return {
4
        restrict: 'E',
5
        scope: {
6
            data: '='
7
        },
8
        templateUrl: 'templates/book-widget.html'
9
    }
10
})

directive function has been used in the above example to create a directive first. The name of the directive is bookThis directive returns an object, and let's talk a bit about this object. restrict is for defining the directive type, and it can be A (Attribute), C (Class), E (Element), and M (coMment). You can see the usage of each respectively below.

Type Usage
A <div book></div>
C <div class="book"></div>
E <book data="book_data"></book>
M <!--directive:book -->

scope is for managing the directive scope. In the above case, book data is transferred to the directive template by using the "=" scope type. I will talk about in detail about scope in the following sections. templateUrl is used for calling a view in order to render specific content by using data transferred to the directive scope. You can also use template and provide HTML code directly, like this:

1
.....
2
template: '<div>Book Info</div>'
3
.....

In our case, we have a complicated HTML structure, and that is why I chose the templateUrl option.

2. Directive Restrictions

Directives are defined in the JavaScript file of your AngularJS project and used in the HTML page. It is possible to use AngularJS directives in HTML pages as follows:

A (Attribute)

In this usage, the directive name is used inside standard HTML elements. Let say that you have a role-based menu in your eCommerce application. This menu is formed according to your current role. You can define a directive to decide whether the current menu should be displayed or not. Your HTML menu may be like below:

1
<ul>
2
    <li>Home</li>
3
    <li>Latest News</li>
4
    <li restricted>User Administration</li>
5
    <li restricted>Campaign Management</li>
6
</ul>

and the directive as follows:

1
app.directive("restricted", function() {
2
    return {
3
        restrict: 'A',
4
        link: function(scope, element, attrs) {
5
            // Some auth check function

6
            var isAuthorized = checkAuthorization();
7
            if (!isAuthorized) {
8
                element.css('display', 'none');
9
            }
10
        }
11
    }
12
})

If you use the restricted directive in the menu element as an attribute, you can do an access level check for each menu. If the current user is not authorized, that specific menu will not be shown. 

So, what is the link function there? Simply, the link function is the function that you can use to perform directive-specific operations. The directive is not only rendering some HTML code by providing some inputs. You can also bind functions to the directive element, call a service and update the directive value, get directive attributes if it is an E type directive, etc.

C (Class)

You can use the directive name inside HTML element classes. Assuming that you will use the above directive as Cyou can update the directive restrict as C and use it as follows:

1
<ul>
2
    <li>Home</li>
3
    <li>Latest News</li>
4
    <li class="nav restricted">User Administration</li>
5
    <li class="nav active restricted">Campaign Management</li>
6
</ul>

Each element already has a class for styling, and as the restricted class is added it is actually a directive.

E (Element)

You don't need to use a directive inside an HTML element. You can create your own element by using an AngularJS directive with an E restriction. Let's say that you have a user widget in your application to show username, avatar, and reputation in several places in your application. You may want to use a directive like this:

1
app.directive("user", function() {
2
    return {
3
        restrict: 'E',
4
        link: function(scope, element, attrs) {
5
            scope.username = attrs.username;
6
            scope.avatar = attrs.avatar;
7
            scope.reputation = attrs.reputation;
8
        },
9
        template: '<div>Username: {{username}}, Avatar: {{avatar}}, Reputation: {{reputation}}</div>'
10
    }
11
})

The HTML code will be:

1
<user username="huseyinbabal" avatar="https://www.gravatar.com/avatar/ef36a722788f5d852e2635113b2b6b84?s=128&d=identicon&r=PG" reputation="8012"></user>

In the above example, a custom element is created and some attributes are provided like username, avatar, and reputation. I want to draw attention to the link function body. Element attributes are assigned to directive scope. The first parameter of the link function is the scope of the current directive. The third parameter of the directive is the attribute object of the directive, which means that you can read any attribute from the custom directive by using attrs.attr_name. Attribute values are assigned to the scope so that they are used inside the template. 

Actually, you can do this operation in a shorter way, and I will talk about that later. This example is for understanding the main idea behind usage.

M (coMment)

This usage is not very common, but I will show how to use it. Let's say that you need a comment form for your application to use in many places. You can do that by using the following directive:

1
app.directive("comment", function() {
2
    return {
3
        restrict: 'M',
4
        template: '<textarea class="comment"></textarea>'
5
    }
6
})

And in the HTML element:

1
<!-- directive:comment -->

3. Isolated Scope

Every directive has its own scope, but you need to be careful about the data binding with the directive declaration. Let say that you are implementing the basket part of your eCommerce application. On the basket page you have items already added here before. Each item has its amount field to select how many items you want to buy, like below:

Simple CartSimple CartSimple Cart

Here's the directive declaration:

1
app.directive("item", function() {
2
    return {
3
        restrict: 'E',
4
        link: function(scope, element, attrs) {
5
            scope.name = attrs.name;
6
        },
7
        template: '<div><strong>Name:</strong> {{name}} <strong>Select Amount:</strong> <select name="count" ng-model="count"><option value="1">1</option><option value="2">2</option></select> <strong>Selected Amount:</strong> {{count}}</div>'
8
    }
9
})

And in order to display three items in HTML:

1
<item name="Item-1"></item>
2
<item name="Item-2"></item>
3
<item name="Item-3"></item>

The problem here is that whenever you choose the amount of the desired item, all the amount sections of the items will be updated. Why? Because there is two-way data binding with a name count, but scope is not isolated. In order to isolate scope, just add scope: {} to the directive attribute in the return section:

1
app.directive("item", function() {
2
    return {
3
        restrict: 'E',
4
        scope: {},
5
        link: function(scope, element, attrs) {
6
            scope.name = attrs.name;
7
        },
8
        template: '<div><strong>Name:</strong> {{name}} <strong>Select Amount:</strong> <select name="count" ng-model="count"><option value="1">1</option><option value="2">2</option></select> <strong>Selected Amount:</strong> {{count}}</div>'
9
    }
10
})

This leads your directive to have its own isolated scope so two-way data binding will occur inside this directive separately. I will also mention about the scope attribute later.

4. Directive Scopes

The main advantage of the directive is that it's a reusable component that can be used easily—you can even provide some additional attributes to that directive. But, how is it possible to pass additional value, binding, or expression to a directive in order for data to be used inside the directive?

"@" Scope: This type of scope is used for passing value to the directive scope. Let's say that you want to create a widget for a notification message:

1
app.controller("MessageCtrl", function() {
2
    $scope.message = "Product created!";
3
})
4
app.directive("notification", function() {
5
    return {
6
        restrict: 'E',
7
        scope: {
8
            message: '@'
9
        },
10
        template: '<div class="alert">{{message}}</div>'
11
    }
12
});

and you can use:

1
<notification message="{{message}}"></notification>

In this example, the message value is simply assigned to the directive scope. The rendered HTML content will be:

1
<div class="alert">Product created!</div>

"=" Scope: In this scope type, scope variables are passed instead of the values, which means that we will not pass {{message}}, we will pass message instead. The reason behind this feature is constructing two-way data binding between the directive and the page elements or controllers. Let's see it in action.

1
.directive("bookComment", function() {
2
    return {
3
        restrict: 'E',
4
        scope: {
5
            text: '='
6
        },
7
        template: '<input type="text" ng-model="text"/>'
8
    }
9
})

In this directive, we are trying to create a widget for displaying comment text input to make a comment for a specific book. As you can see, this directive requires one attribute text to construct two-way data binding between other elements on the pages. You can use this on the page:

1
<span>This is the textbox on the directive</span>
2
<book-comment text="commentText"></book-comment>

This will simply show a textbox on the page, so let's add something more to interact with this directive:

1
<span>This is the textbox on the page</span>
2
<input type="text" ng-model="commentText"/>
3
<br/>
4
<span>This is the textbox on the directive</span>
5
<book-comment text="commentText"></book-comment>

Whenever you type something in the first text box, it will be typed also in the second text box. You can do that vice versa. In the directive, we passed the scope variable commentText instead of the value, and this variable is the data binding reference to the first text box. 

"&" Scope: We are able to pass the value, and reference to directives. In this scope type we will have a look at how to pass expressions to the directive. In real-life cases, you may need to pass a specific function (expression) to directives in order to prevent coupling. Sometimes, directives do not need to know much about the idea behind the expressions. For example, a directive will like the book for you, but it doesn't know how to do that. In order to do that, you can follow a structure like this:

1
.directive("likeBook", function() {
2
    return {
3
        restrict: 'E',
4
        scope: {
5
            like: '&'
6
        },
7
        template: '<input type="button" ng-click="like()" value="Like"/>'
8
    }
9
})

In this directive, an expression will be passed to the directive button via the like attribute. Let's define a function in the controller and pass it to the directive inside the HTML.

1
$scope.likeFunction = function() {
2
    alert("I like the book!")
3
}

This will be inside the controller, and the template will be:

1
<like-book like="likeFunction()"></like-book>

likeFunction() comes from the controller and is passed to the directive. What if you want to pass a parameter to likeFunction()? For example, you may need to pass a rating value to the likeFunction(). It is very simple: just add an argument to the function inside the controller, and add an input element to the directive to require start count from the user. You can do that as shown below:

1
.directive("likeBook", function() {
2
    return {
3
        restrict: 'E',
4
        scope: {
5
            like: '&'
6
        },
7
        template: '<input type="text" ng-model="starCount" placeholder="Enter rate count here"/><br/>' +
8
        '<input type="button" ng-click="like({star: starCount})" value="Like"/>'
9
    }
10
})
1
$scope.likeFunction = function(star) {
2
    alert("I like the book!, and gave " + star + " star.")
3
}
1
<like-book like="likeFunction(star)"></like-book>

As you can see, the text box comes from the directive. The text box value is bound to the function argument like like({star: starCount}). star is for the controller function, and starCount for the textbox value binding. 

5. Directive Inheritance

Sometimes, you may have a feature that exists in several directives. They can be put in a parent directive so that they are inherited by the child directives. 

Let me give you a real-life example. You want to send statistical data whenever customers move their mouse cursor to the top of a specific book. You can implement a mouse click event for the book directive, but what if it will be used by another directive? In this case, you can use inheritance of the directives like below:

1
app.directive('mouseClicked', function() {
2
    return {
3
        restrict: 'E',
4
        scope: {},
5
        controller: "MouseClickedCtrl as mouseClicked"
6
    }
7
})

This is a parent directive to be inherited by child directives. As you can see there is a controller attribute of the directive using the "as" directive. Let's define this controller also:

1
app.controller('MouseClickedCtrl', function($element) {
2
    var mouseClicked = this;
3
4
    mouseClicked.bookType = null;
5
6
    mouseClicked.setBookType = function(type) {
7
        mouseClicked.bookType = type
8
    };
9
10
    $element.bind("click", function() {
11
        alert("Typeof book: " + mouseClicked.bookType + " sent for statistical analysis!");
12
    })
13
})

In this controller, we are simply setting a controller instance of the variable bookType by using child directives. Whenever you click a book or magazine, the type of element will be sent to the back-end service (I used an alert function just to show the data). How will child directives be able to use this directive?

1
app.directive('ebook', function() {
2
    return {
3
        require: "mouseClicked",
4
        link: function(scope, element, attrs, mouseClickedCtrl) {
5
            mouseClickedCtrl.setBookType("EBOOK");
6
        }
7
    }
8
})
9
.directive('magazine', function() {
10
    return {
11
        require: "mouseClicked",
12
        link: function(scope, element, attrs, mouseClickedCtrl) {
13
            mouseClickedCtrl.setBookType("MAGAZINE");
14
        }
15
    }
16
})

As you can see, child directives use the require keyword to use the parent directive. And one more important point is the fourth argument of the link function in the child directives. This argument refers to the controller attribute of the parent directive that means the child directive can use the controller function setBookType inside the controller. If the current element is an eBook, you can use the first directive, and if it is a magazine, you can use the second one:

1
<a><mouse-clicked ebook>Game of thrones (click me)</mouse-clicked></a><br/>
2
<a><mouse-clicked magazine>PC World (click me)</mouse-clicked></a>

Child directives are like a property of the parent directive. We have eliminated the usage of the mouse-click event for each child directive by putting that section inside the parent directive.

6. Directive Debugging

When you use directives inside the template, what you see on the page is the compiled version of the directive. Sometimes, you want to see the actual directive usage for debugging purposes. In order to see the uncompiled version of the current section, you can use ng-non-bindable. For example, let's say you have a widget that prints the most popular books, and here is the code for that:

1
<ul>
2
    <li ng-repeat="book in books">{{book}}</li>
3
</ul>

The book's scope variable comes from the controller, and the output of this is as follows:

If you want to know the directive usage behind this compiled output, you can use this version of the code:

1
<ul ng-non-bindable="">
2
    <li ng-repeat="book in books">{{book}}</li>
3
</ul>

This time the output will be like below:

It is cool up to now, but what if we want to see both the uncompiled and compiled versions of the widget? It is time to write a custom directive that will do an advanced debugging operation. 

1
app.directive('customDebug', function($compile) {
2
    return {
3
        terminal: true,
4
        link: function(scope, element) {
5
            var currentElement = element.clone();
6
            currentElement.removeAttr("custom-debug");
7
            var newElement = $compile(currentElement)(scope);
8
            element.attr("style", "border: 1px solid red");
9
            element.after(newElement);
10
        }
11
    }
12
})

In this directive, we are cloning the element that's in debug mode so that it's not changed after some set of operations. After cloning, remove the custom-debug directive in order not to act as debug mode, and then compile it with $complile, which is already injected in the directive. We have given a style to the debug mode element to emphasize the debugged one. The final result will be as below:

Sample DirectiveSample DirectiveSample Directive

You can save your development time by using this kind of debugging directive to detect the root cause of any error in your project.

7. Directive Unit Testing

As you already know, unit testing is a very important part of development to totally control the code you have written and prevent potential bugs. I will not dive deep into unit testing but will give you a clue about how to test directives in a couple of ways.

I will use Jasmine for unit testing and Karma for the unit test runner. In order to use Karma, simply install it globally by running npm install -g karma karma-cli (you need to have Node.js and npm installed on your computer). After installation, open the command line, go to your project root folder, and type karma init. It will ask you a couple of questions like below in order to set up your test requirements.

Karma Test InitializationKarma Test InitializationKarma Test Initialization

I am using Webstorm for development, and if you are also using Webstorm, just right click on karma.conf.js and select Run karma.conf.js. This will execute all the tests that are configured in the karma conf. You can also run tests with the karma start command line in the project root folder. That's all about the environment setup, so let's switch to the test part.

Let's say that we want to test the book directive. When we pass a title to the directive, it should be compiled into a book detail view. So, let's get started.

1
describe("Book Tests", function() {
2
    var element;
3
    var scope;
4
    beforeEach(module("masteringAngularJsDirectives"))
5
    beforeEach(inject(function($compile, $rootScope) {
6
        scope = $rootScope;
7
        element = angular.element("<booktest title='test'></booktest>");
8
        $compile(element)($rootScope)
9
        scope.$digest()
10
    }));
11
12
    it("directive should be successfully compiled", function() {
13
        expect(element.html()).toBe("test")
14
    })
15
});

In the above test, we are testing a new directive called booktestThis directive takes the argument title and creates a div by using this title. In the test, before each test section, we are calling our module masteringAngularJsDirectives first. Then, we are generating a directive called booktest.  In each test step, the directive output will be tested. This test is just for a value check.

8. Directive Scope Testing

In this section, we will test the scope of the directive booktestThis directive generates a book detail view on the page, and when you click this detail section, a scope variable called viewed will be set as true. In our test, we will check if viewed is set to true when the click event is triggered. The directive is:

1
.directive('booktest', function() {
2
    return {
3
        restrict: 'E',
4
        scope: {
5
            title: '@'
6
        },
7
        replace: true,
8
        template: '<div>{{title}}</div>',
9
        link: function(scope, element, attrs) {
10
            element.bind("click", function() {
11
                console.log("book viewed!");
12
                scope.viewed = true;
13
            });
14
        }
15
    }
16
})

In order to set an event to an element in AngularJS inside the directive, you can use the link attribute. Inside this attribute, you have the current element, directly bound to a click event. In order to test this directive, you can use the following:

1
describe("Book Tests", function() {
2
    var element;
3
    var scope;
4
    beforeEach(module("masteringAngularJsDirectives"))
5
    beforeEach(inject(function($compile, $rootScope) {
6
        scope = $rootScope;
7
        element = angular.element("<booktest title='test'></booktest>");
8
        $compile(element)($rootScope)
9
        scope.$digest()
10
    }));
11
12
    it("scope liked should be true when book liked", function() {
13
        element.triggerHandler("click");
14
        expect(element.isolateScope().viewed).toBe(true);
15
    });
16
});

In the test section, a click event is triggered by using element.triggerHandler("click"). When a click event is triggered, the viewed variable needs to be set as true. That value is asserted by using expect(element.isolateScope().viewed).toBe(true).

9. Conclusion

In order to develop modular and testable web projects, AngularJS is the best one in common. Directives are one of the best components of AngularJS, and this means the more you know about AngularJS directives, the more modular and testable projects you can develop. 

In this tutorial, I have tried to show you the real-life best practices about directives, and keep in mind that you need to do lots of practice in order to understand the logic behind the directives. I hope this article helps you understand AngularJS directives well.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.