Reputation: 4870
I want to compile an AngularJS template to plain text. I.e. I want to get what you would get by reading the inner HTML of a template rendered in the DOM on the page. But without actually rendering the template to the page.
I have tried using $compile
like this
$compile(template)($scope).html()
But it does not seem to work as expected as demonstrated in this jsFiddle. The result both in the jsFiddle and in my project is nothing but a comment inserted by Angular.
What is the proper way to compile an Angular template and getting the result back as an HTML string?
In case anyone are curious why I need to do this: The rendered HTML will be sent to the backend which converts it to a pdf-file that is sent back again.
Upvotes: 2
Views: 833
Reputation: 1581
If you want the final output with the scope applied to the view I believe you have to wait until the $digest
call is completed.
I updated the fiddle to write the finished HTML to the console. I used a setTimeout() to wait until the $digest
call was completed and it displayed the actual result that would be displayed in the HTML.
Upvotes: 2
Reputation: 108481
Something like this ought to do. The isolated scope is optional I suppose, but any model you have will need to be a part of a Scope
:
var template = '<div ng-repeat="item in items">{{item}}</div>',
element = angular.element(template ),
scope = $rootScope.$new(true); //isolated scope
scope.items = ['foo', 'bar', 'frob'];
// apply bindings!
$compile(template)(scope);
var html = template[0].outerHTML;
Upvotes: 0