As I'm new to Angular JS I was wondering how could I load an external template and compile it with some data into the targeted div
.
For instance I have this template :
<script type="text/ng-template">
<img src="{{Thumb}}" />
<script>
The div
that is supposed to contain the template :
<div data-ng-controller=" ... "></div>
The template is located somewhere in a folder /templates/test.php
. Is there a build in way of doing the template loading like a directive would do and compile it against some data that would replace the key {{Thumb}}
( and many others of course ) ?
EDIT : What if I use $routes
and load a template when I'm in the root of the website ? How could that be achieved ?
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. If you have a static string like in this
// example, you might as well omit the $sce call.
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 here
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With