Load HTML template from file to variable in AngularJs

I am working with a form that should bind HTML to a Rich Text Editor. The best way to save this HTML content is to use an HTML file.

I cannot figure out how to load an HTML template from a file and assign it to a variable.

Directives seem to be able to do this when working with templateUrl. I wonder if it has any low level api in angular to achieve the same inside the controller.

+43
angularjs
Jun 30 '14 at 18:02
source share
2 answers

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

app.controller('testCtrl', function($scope, $templateCache){ var template = $templateCache.get('nameOfTemplate.html'); }); 
+52
Jun 30 '14 at 18:08
source share

Using $templateRequest , you can download the template by URL without having to embed it in your HTML page. If the template is already loaded, it will be displayed 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 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 }); }); 

Remember that this is a manual way to do this, and in most cases the preferred way is to define a directive , which retrieves the template using the templateUrl property.

+76
Apr 19 '15 at 22:47
source share



All Articles