How to use AngularJS $templateCache.get()?

12,632

Solution 1

You have to fetch html using http request then you can store it in template cache. For example:

$http.get('templ.html', {
    cache: $templateCache
}).then(function(result) {
    console.log(result);
});

Updated plunker code here

Solution 2

You can use $templateRequest to fetch the template.

The $templateRequest service runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown (the exception can be thwarted by setting the 2nd parameter of the function to true). Note that the contents of $templateCache are trusted, so the call to $sce.getTrustedUrl(tpl) is omitted when tpl is of type string and $templateCache has the matching entry.

Documentation: https://docs.angularjs.org/api/ng/service/$templateRequest

Share:
12,632
HoffZ
Author by

HoffZ

Updated on June 04, 2022

Comments

  • HoffZ
    HoffZ almost 2 years

    I need to cache some HTML files when my Angular controller initializes.

    According to Angular $templateCache documentation I can add HTML templates to Angular with:

    $templateCache.get('templateId.html')
    

    But I can't get this to work. I've tried to get the template file within the controller and within the module run() function (Plunker). But I can see in the network console that the template is not fetched.

    app.run(function($templateCache) {
      $templateCache.get('templ.html');
    });
    

    What am I doing wrong?