- AngularJS provides $tempateCache module for caching templates.
- This module has put() and get() methods to save and retrieve HTML template from the cache.
- In this Demo, "We will create a simple directive which uses the template cache to load the template string",
- Below code shows the use of template cache to load a template and used in the directive definition.
<!DOCTYPE html> <html ng-app="myApp"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body ng-controller="MainCtrl"> <div ng-repeat="item in studentList"> <name-italic targettext="item"> </name-italic> </div> <script> var myApp = angular.module('myApp', []); var mainController = myApp.controller('MainCtrl', function($scope) { $scope.studentList = ["sandeep", "surabhi", "sangeeta", "sumant", "bapi"]; }); myApp.run(['$http', '$templateCache', function($http, $templateCache) { $templateCache.put('NAMEITALICTEMPLATE', "<i>{{myText}}</i>"); } ]); myApp.directive("nameItalic", ['$templateCache', function($templateCache) { return { restrict: 'E', replace: false, scope: { myText: '=targettext' }, template: $templateCache.get('NAMEITALICTEMPLATE') }; } ]); </script> </body> </html>
- The code for the demo is available in the below embedded fiddle.