AngularJS directives – The basics

AngularJS directives tutorial

Posted on November 13, 2013


Angular JS

Angular Directives are a great way to split your code into manageable blocks for use in multiple templates.

Directives are basically a marker within the DOM than loads a template when found.

For example, if we create the following simple directive

myApp.directive('mydirectivename', function(){
		restrict: 'E',
		template: "

Hi {{name}}, I'm a directive
", link: function (scope, element, attrs) { = 'Marc'; } } })

And then add the directive to a template as below:


The directive will output

<div>Hi Marc, I'm a directive</div>

Restrict option

The restrict option alows you to specify whether the directive will be used as an element, attribute or class

A – Attribute e.g. <div mydirectivename></div>
E – element e.g. <mydirectivename></mydirectivename>
C – Class e.g. <div class=”mydirectivename”></div>
M – Comment e.g. <!– directive: mydirectivename –>

Template option

As well as adding your template inline you also have the option of using templateUrl to load a template with ajax:

templateUrl: 'templates/my-template.html'

Link Option

You can modify the DOM using the link() function. In this case we’re just passing a name.

AngularJS Directives have a number of other options which I’ll cover in a later post.