In AngularJS, the templateUrl
property allows us to load external HTML templates into directives. This approach is useful for keeping the directive’s template separate from the JavaScript logic, improving code modularity, reusability, and maintainability.
Step 1: Why Use templateUrl
?
- Separation of concerns → Keeps HTML structure separate from JavaScript logic.
- Reusability → The same template can be used across multiple directives.
- Maintainability → Changes in the template don’t require changes in the directive definition.
- Better readability → Makes the directive’s JavaScript cleaner.
Step 2: Creating a Directive with templateUrl
Example – Loading an External Template
Let’s create a simple directive that loads an external HTML template.
1️⃣ HTML (index.html)
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<title>Directive with templateUrl</title>
</head>
<body ng-controller="MainCtrl">
<custom-directive></custom-directive> <!-- Custom directive loads template -->
<script src="app.js"></script> <!-- Main AngularJS file -->
</body>
</html>
2️⃣ External Template (template.html)
<div class="custom-template">
<h2>{{ title }}</h2>
<p>{{ description }}</p>
</div>
3️⃣ AngularJS Directive (app.js)
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.title = "AngularJS Directive Example";
$scope.description = "This template is loaded using templateUrl.";
});
app.directive('customDirective', function() {
return {
restrict: 'E',
scope: {
title: '@',
description: '@'
},
templateUrl: 'template.html'
};
});
Step 3: How It Works?
- Directive (
customDirective
) is used as an element (restrict: 'E'
). templateUrl
loadstemplate.html
dynamically.- Scope variables (
title
&description
) are passed using@
binding. - AngularJS fetches the template via an HTTP request.
Step 4: Handling templateUrl
with Controllers
If the directive needs its own controller, you can include it inside the directive definition.
Example – Using a Controller in a Directive
app.directive('customDirective', function() {
return {
restrict: 'E',
scope: {},
templateUrl: 'template.html',
controller: function($scope) {
$scope.title = "Directive with Controller";
$scope.description = "This directive has its own controller.";
}
};
});
Now, the directive manages its own data, instead of relying on the parent controller.
Step 5: Passing Dynamic Data into templateUrl
Directive
To pass dynamic data into the directive, use scope
binding.
Example – Passing Data from Parent Scope
1️⃣ Updated HTML
<custom-directive title="Dynamic Title" description="This is passed from HTML"></custom-directive>
2️⃣ Updated Directive
app.directive('customDirective', function() {
return {
restrict: 'E',
scope: {
title: '@',
description: '@'
},
templateUrl: 'template.html'
};
});
Data is passed dynamically using attributes (@
binding).
Step 6: Using templateUrl
with ng-repeat
Example – Displaying a List with ng-repeat
1️⃣ External Template (list-template.html
)
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
2️⃣ Updated Directive
app.directive('listDirective', function() {
return {
restrict: 'E',
scope: {
items: '='
},
templateUrl: 'list-template.html'
};
});
3️⃣ Using the Directive
<list-directive items="fruits"></list-directive>
4️⃣ Data in Controller
app.controller('MainCtrl', function($scope) {
$scope.fruits = ["Apple", "Banana", "Mango", "Orange"];
});
The list dynamically updates based on fruits
in the controller.
Step 7: Caching Templates for Performance
By default, AngularJS fetches templates using an HTTP request. To avoid repeated requests, use $templateCache
.
Example – Preloading a Template
app.run(function($templateCache) {
$templateCache.put('cached-template.html', '<p>This is a cached template.</p>');
});
app.directive('cachedDirective', function($templateCache) {
return {
restrict: 'E',
template: $templateCache.get('cached-template.html')
};
});
This method avoids an extra HTTP request and improves performance.
Step 8: Error Handling in templateUrl
If the template fails to load, it can cause issues. Use $http
to handle errors.
Example – Handling Template Loading Errors
app.directive('safeDirective', function($http) {
return {
restrict: 'E',
templateUrl: 'nonexistent.html',
link: function(scope, element) {
$http.get('nonexistent.html').catch(function() {
element.html('<p>Error loading template.</p>');
});
}
};
});
If the template fails to load, an error message appears.