How To Build A Simple Angular Directive

Quick - Use a directive to encapsulate the modified light box

I knew what I wanted to do. I have a heavily modified light box that I have used with jQuery for a while. I was converting a site from jQuery to AngularJS and I needed it. I knew that Angular directives are the way to use existing components inside Angular. I figure that it would take 30 minutes or an hour and I would be able to move on.

Boy was I wrong. Directives in Angular are way more important, complex and subtle than a quick hour long project. I spent a day just reading and learning and I had not even begun to touch the surface of what directives can do.

That is how this set of articles was born. I could not find a really detailed guide that covered directives for the newbie from the very basic all the way to building extensions to Angular.

What are directives and how are they used.

Directives are used inside Angular to set up interactions between the DOM and the scope. In the angular framework ng-click, ng-repeat and ng-model are all directives. This means that you have been using them without even knowing it.

Directives can be used to modify and extend the behavior of existing HTML elements. For example, select, input and textarea are all directives. If you want to take an exiting HTML tag and get rid of that weird behavior that you don't really like, then directives are the way to go.

You can build your own HTML tags too. The simple example in this article will build a custom HTML tag. This allows for the building of reusable components that are cleanly encapsulated.

Directives are also used as an interface to existing components. That was my original plan to take my existing jQuery plug in and just package it up as a directive and use it.

Directives are the heart and soul of Angular. To me that means that I must truly understand them if I want to use Angular to its full potential.

A really simple directive

This is a really simple directive. A complete explanation of it will follow. I will build on the simple directive and create a Bootstrap menu bar before the end of the article.

Example (example1.html):

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="app">
<head>
	<link rel="stylesheet" type="text/css" href="./css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="./css/bootstrap-responsive.css">
	<script src="./js/angular.js"></script>
    <script type="text/javascript">
        // Simple App: won't do anything  ------------------------------------------------------------------------------------
        var app = angular.module( "app", [] );
        // Simple Controler: won't do anyting  -------------------------------------------------------------------------------
        app.controller( "AppController", function( $scope ){
		});
	</script> 
</head>
<body>

example1:.html -- this should not do anyting.  Also no errors.<br>

<div ng-controller="AppController">
	<myTitle></myTitle>
</div>

</body>
</html>



The important chunk that is not just regular Angular is the <myTitle></myTitle>. The rest of the file is just the regular stuff that you need to get off the ground with Angular and Bootstrap. All of the files are included in the download including a very short "serve-it.js" file that you can run with node as a static file server.

Now let's make it actually do something. How about a simple title as a h3 element. We will add more to it later and then transform it into a more complex directive.

Example (example2.html):

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="app">
<head>
	<link rel="stylesheet" type="text/css" href="./css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="./css/bootstrap-responsive.css">
	<script src="./js/angular.js"></script>
    <script type="text/javascript">
        // Simple App: won't do anything  ------------------------------------------------------------------------------------
        var app = angular.module( "app", [] );
        // Simple Controler: won't do anyting  -------------------------------------------------------------------------------
        app.controller( "AppController", function( $scope ){
		});
		// Finally - we create a really simple directive ---------------------------------------------------------------------
        app.directive( "myTitle", function() {
			return({
				  restrict: "E"
        		, replace: true
				, link: function (scope, element, attrs) {
					element.prepend("<div class='title'>" + attrs.title + "</div>");
				  }
			});
		});
	</script> 
</head>
<body>

example2:.html -- this should not do a little.<br>

<div ng-controller="AppController">
	<my-title title="Who am I"></my-title>
</div>

</body>
</html>



A very long break from this article

It is embarasing to say - but 2 months have gone by and I have not finished this quick project. It is now mid December and I am back to working on this.

My requirements for implementation have changed a little. I now have a variety of somewhat similar gallary components that I want to build using AngularJS.


•       •       •       •       •       •

Summary: # of Words: 696
Author: Philip J. Schlump
Published On: 2013-10-16

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens