56

I'm working with a form that needs to bind HTML to a Rich Text Editor. The best way to store this HTML content would be an HTML file.

I can't quite figure out how to load an HTML template from a file and assign it to a variable.

Directives seem to do be able to do this when working with templateUrl. Was wondering if this there is any low level api in angular to achieve the same thing inside of a controller

dmullings
  • 7,070
  • 5
  • 28
  • 28
Abhinav Gujjar
  • 2,570
  • 2
  • 25
  • 35

2 Answers2

95

Using $templateRequest, you can load a template by it’s URL without having to embed it into your HTML page. If the template is already loaded, it will be taken from the cache.

app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
    // Make sure that no bad URLs are fetched. You can omit this if your template URL is
    // not dynamic.
    var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');

    $templateRequest(templateUrl).then(function(template) {
        // template is the HTML template as a string

        // Let's put it into an HTML element and parse any directives and expressions
        // in the code. (Note: This is just an example, modifying the DOM from within
        // a controller is considered bad style.)
        $compile($("#my-element").html(template).contents())($scope);
    }, function() {
        // An error has occurred
    });
});

Be aware that this is the manual way to do it, and whereas in most cases the preferable way would be to define a directive that fetches the template using the templateUrl property.

cdauth
  • 6,171
  • 3
  • 41
  • 49
62

All templates are loaded into a cache. There is an injectable $templateCache service you can use to get access to the templates:

app.controller('testCtrl', function($scope, $templateCache){
    var template = $templateCache.get('nameOfTemplate.html');
});
dustyrockpyle
  • 3,184
  • 17
  • 12
  • 1
    This seems to work if the template is defined inline using – Abhinav Gujjar Jun 30 '14 at 18:19
  • 5
    How did you want to fetch your templates? You can also do `` . Or you can use the $http service to manually fetch the templates and use `$templateCache.put` to store them. – dustyrockpyle Jun 30 '14 at 18:38
  • ok - perfect. This covers the scenario I was looking for. Thanks! – Abhinav Gujjar Jun 30 '14 at 20:06
  • My debugger is telling me that it cannot get "get of undefined". Say I have multiple blogs and I want to return them based on the ":param" attribute in the route provider. Would this be one of the ways you can specify this with $templateCache? – Coded Container Sep 25 '15 at 14:50
  • @dustyrockpyle Can't works with separate file, only if template inside script tag – Mediator Feb 18 '16 at 05:32
  • I was worried the template might not be in the cache when I ''get' it, but it seems this is no issue, the template is loaded correctly regardless of previously not accessing / using it. – jediz Sep 06 '16 at 10:21