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)
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
Pre-linking function Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Post-linking function Executed after the child elements are linked.
Angular introduces a new property to the directive definition object called bindToController. BindToController enables the inherited properties to be bound to the Controller without $scope object.
Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned. Compile: traverse the DOM and collect all of the directives.
Sure, 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>
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