<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> </head> <body ng-app="mainModule"> <div ng-controller="mainController"> <h3>1. Template</h3> <div ngh-template-dir> <strong>This content will be replaced</strong> <div> This one will be replaced too </div> </div> <br /> <h3>2. TemplateUrl</h3> <div ngh-template-url-dir> <strong>This content will be replaced</strong> <div> This one will be replaced too </div> </div> </div> </body> </html>
angular.module("mainModule", []) .controller("mainController", function ($scope) { $scope.myScopeVar = "the scope variable value"; }) // 1. Directive with a template specified inline .directive("nghTemplateDir", function () { return { template: 'This is <strong>nghTemplateDir</strong> directive printing <em>{{myScopeVar}}</em>' }; }) // 2. Directive with a template loaded from a URL .directive("nghTemplateUrlDir", function () { return { templateUrl: 'nghTemplateUrlDirBody.html' }; });
This is <strong>nghTemplateUrlDir</strong> directive printing <em>{{myScopeVar}}</em>



If the custom directive has to add some HTML markup that always has the same structure, it is convenient to specify it through the template or templateUrl properties of the directive's definition object.

In point 1 of the example we see how we can add our own HTML template by specifying it as an inline value of the template property, while point 2 loads the template from a URL, in this case from the external nghTemplateUrlDirBody.html file specified as a value of the templateUrl property.

The content of the template is added to the DOM tree during the compilation phase so each AngularJS specific markup inside the template is evaluated because the evaluation happens after the HTML has been fully compiled (in the example you see that in the templates we use the curly braces to evaluate the value of a scope variable).

NOTE: AngularJS replaces the content of the DOM node where the directive appears with the content of the specified template, so as you can see in the example, the original HTML markup inside the div elements with the directives is completely replaced by the templates.