Tutorial: Creating Reusable Code with AngularJS Directives

AngularJS Directives

I know this may not be new for most of you, but when it comes to directives a lot of people still get really confused, so let’s start by looking at its definition, according to AngularJS documentacion:

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

In other words, they allow us to create our own DOM elements that can be reused all over the place, imagine that you have a block of HTML code that you know you’re going to use in several places, instead of just coping and pasting it everywhere, you can create a directive and use it wherever you need, it’ll be a lot easier for you to maintain your code, if something changes in this HTML block you just have to modify your directive, and the changes will reflect across your application.

It will be easier to understand with an example, let’s create a project containing the following files:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html ng-app="directivesTutorial">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="app/resources/js/app.js" type="text/javascript"></script>
    </head>
    <body >
        <div ng-controller="directivesTutorialController">
            <div ng-repeat="company in companies">
                <p>Company: {{company.name}} - City: {{company.city}}</p>
            </div>
        </div>
    </body>
</html>

app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
var app = angular.module('directivesTutorial', []);
app.controller('directivesTutorialController', function ($scope, $http) {
    $scope.companies = [{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}];
});

Nothing different for now, we’ve seen this a million times, it’s just a ng-repeat iterating over a JSON (in this case a list of campanies), note that inside the ng-repeat div we have a small block of code that displays the company information, of course this block would be more complex in a real scenario, but let’s suppose we need to reuse it to display the same data in other parts of the application, to achieve that we’re going create a directive called ‘company’ which will be responsible for displaying the company data.

Copy the code bellow to another js file, let’s call it ‘campany.js':

1
2
3
4
5
6
7
8
var companyDirective = angular.module('directives.company', []);
companyDirective.directive('company', function () {
    return{
        retrict: 'E',
        scope: {object: '='},
        templateUrl: "templates/company.html"
    };
});

That’s our directive’s code, you can see that it returns an object containing 3 attributes, the first one is the “retrict: ‘E'”, it means that our directive will be restricted to elements, in other words it will be a DOM element.

The second one is the “object: ‘='”, by declaring this ‘object’ variable we’re saying that our directive will have an attribute called ‘object’, we’re going to use this attribute to pass the company we want the data to be displayed.
And lastly we have our templateUrl that receives the path to an html file containing the directive’s html code.

Our company.html should look like this:

1
<p>Company: {{object.name}} - City: {{object.city}}</p>

Note that it’s the same code as before, the only difference is that instead of using the variable ‘company’ we’re using ‘object’ which is the name of the attribute we defined before.

We’re almost done, now you just have to add to your index.html a reference to company.js:

1
<script src="{YOUR_PATH}/company.js" type="text/javascript"></script>

and also put the directive as a dependency in your app.js:

1
var app = angular.module('directivesTutorial', ['directives.company']);

That’s it! Now our ng-repeat can be rewritten using our new directive:

1
2
3
<div ng-repeat="company in companies">
    <company object="company"></company>
</div>

You now have the ‘company’ element that can be reused anywhere in your application.

Related Posts:
Tutorial: Basic DataTable (sorting, filtering and pagination) with AngularJS and ng-Table
Tutorial: Implementing Infinite Scroll with AngularJS and ngInfiniteScroll

Recommended for you

How to Load a JSON file in Javascript In this post I'm going to give you a very simple example of how to read a JSON file and display the data on the page. I'll be using jQuery in this example, so if you don't have it on your project don't forget to add the script. So let's get started, first we need a JSON, you probably already have...
Tutorial: Integrating AngularJS with NodeJS Integrating AngularJS with NodeJS I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it's a very common ...
Node.js Tutorial: Reading and Writing files Reading and writing files is a very trivial task, no matter what programming language you use you probably have already came across a situation where you had to do it, and it's not different for node.js developers, luckily node.js makes this task very easy for us, with the file system(fs) module we ...
Tutorial: Creating AngularJS Services Imagine that you have a project with countless features responsible for performing a huge variety of tasks, if you don't do as much as you can to organize it, how would the code look like? It would be nearly impossible to maintain this project if everything is mixed together in the code, no one woul...

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>