May 7th 2015

AngularJS Directives (part 3)

How to define your Directives' template.

Directive Template
There are two ways to define your Directives' template.

'Template'
Passing a string to the 'template' property will result in the string rendered as your directive template.

//Create a directive called 'My Directive'
app.directive('myDirective', function(){
	return {
		template: "Content of my directive, yo!"
	}
});
Will result in
<my-directive>Content of my directive, yo!</my-directive>


You can even have HTML in your string, which will automatically translate to real elements.
template: "<div>Content of my directive in a div!</div>"
<my-directive>
	<div>Content of my directive in a div!</div>
</my-directive>


'Template URL'
The other (better) option is to load your template from another HTML file.

First, create an HTML file and name it whatever you want. Mine is called 'template.html'.
 <!-- My template.html -->
<div>A fully functioning HTML including <b>bold</b>, <i>italic</i>, <a>anchor tags</a> etc...</div>

Then, load it into your directive using templateUrl.
// Directive object
templateUrl: "template.html"
Will result in
<my-directive>
	<div>A fully functioning HTML including <b>bold</b>, <i>italic</i>, <a>anchor tags</a> etc...</div>
</my-directive>


'Replace'
You can have your template replace your original directive element by using 'replace'
So by default:
//Create a directive called 'My Directive'
app.directive('myDirective', function(){
	return {
		template: "Content of my directive, yo!"
	}
});
Will result in
<my-directive>
	<div>Content of my directive, yo!</div>
</my-directive>


But using 'replace':
//Create a directive called 'My Directive'
app.directive('myDirective', function(){
	return {
		replace: true,
		template: "Content of my directive, yo!"
	}
});
Will result in
<div>Content of my directive, yo!</div>