In my Angular 1.5.11 application, I am trying to programmatically compile a template and get the result as an HTML string. Template Content
<div ng-if="foo">
<div>foo is {{foo}}, bar is {{bar}}</div>
</div>
My attempt to compile it into an HTML string:
app.controller('MainCtrl', function($scope, $rootScope, $compile) {
function compileHtmlTemplate (templateContent, model) {
var templateScope = $rootScope.$new(true);
angular.extend(templateScope, model);
return $compile(templateContent)(templateScope);
}
var templateContent = $('#template').html();
var model = {foo: 'fooValue', bar: 'barValue'};
var compiledHtml = compileHtmlTemplate(templateContent, model);
var htmlAsString = $('<div></div>').html(compiledHtml).html();
$scope.result = htmlAsString;
});
However, as you can see in this Plunker example , it does not work. I need to compile a template, not just interpolate it, because it contains a directive ng-if.
source
share