There is the following way to add HTML dynamically in AngularJS
var template = '<div>{{value}}</div>';
var element = angular.element(template);
placeholder.replaceWith(element);
$compile(element)($scope);
Is it possible to do the same from templateURL or load template separately? (with standard mechanism so that it is cached in $templateCache)
There is the following way to add HTML dynamically in AngularJS
var template = '<div>{{value}}</div>';
var element = angular.element(template);
placeholder.replaceWith(element);
$compile(element)($scope);
Is it possible to do the same from templateURL or load template separately? (with standard mechanism so that it is cached in $templateCache)
Share Improve this question edited Jan 20, 2014 at 0:22 webdev asked Jan 19, 2014 at 23:15 webdevwebdev 7566 silver badges17 bronze badges1 Answer
Reset to default 22Sure, you simply use $http
service to fetch the template and than compile and insert it manually. $http
service will take care of caching implicitly.
PLUNKER
(Simplest) directive:
app.directive('message', [
'$http',
'$compile',
function($http, $compile) {
var tpl = "template.html";
return {
scope: true,
link: function(scope, element, attrs){
scope.message = attrs.message;
$http.get(tpl)
.then(function(response){
element.html($compile(response.data)(scope));
});
}
};
}
]);
View:
<span message="Hi World!"></span>
<span message="My name is Angular."></span>
Directive template (template.html
):
<span>{{message}}</span>