In my Angular 1.5.11 app, I'm trying to programmatically compile a template and get the result as a HTML string. The content of the template is
<div ng-if="foo">
<div>foo is {{foo}}, bar is {{bar}}</div>
</div>
My attempt at compiling it to a 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 doesn't work. I need to compile the template rather than just interpolating it, because it contains an ng-if
directive.