Sanjay Hp Sanjay Hp - 1 month ago 13
Javascript Question

What is angular $templatecache? How can i use in an application to prevent hard refresh every time if i modify any template in an application

What is angular

$template-cache
? How can I use it in an application to prevent hard refresh every time if I modify any template in an application.
Please explain to me with an example.

Answer

$templateCache service is used to store templates (html strings). If you write a directive with templateUrl or use ngInclude directive, angular resolves the path to template and sends network request in runtime to retrieve it. When template arrives, it's put into $templateCache using path as a key. Whenever this same template is requested by a directive next time, the network request is not made and instead the template string is retrieved from the $templateCache.

You can use this $templateCache to put templates there when you angular app starts and in this way you'll save network requests and decrease loading time. For example, like this:

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

There are tasks that can help you do it automatically. For example, grunt-angular-templates for grunt.