javascript - Programmatically compile an Angular template to a HTML string -
in angular 1.5.11 app, i'm trying programmatically compile template , result html string. content of template is
<div ng-if="foo"> <div>foo {{foo}}, bar {{bar}}</div> </div>
my attempt @ compiling 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, can see in plunker example, doesn't work. need compile template rather interpolating it, because contains ng-if
directive.
angular's digest cycle needs complete before you'll have access value. can achieve using $timeout
.
i've used $templatecache
retrieve template since that's official way, that's personal preference.
var app = angular.module('plunker', ['ngsanitize']); app.controller('mainctrl', function($scope, $rootscope, $compile, $timeout, $templatecache) { function compilehtmltemplate (templatecontent, model) { var templatescope = $rootscope.$new(true); angular.extend(templatescope, model); var compiled = $compile(templatecontent)(templatescope); var parent = $("<div>").html(compiled); console.log("won't work! digest hasn't finished:", parent[0].innerhtml); $timeout(function(){ // must wait till angular has finished digest console.log('will work, digest has completed:', parent[0].innerhtml); $scope.result = parent[0].innerhtml; }, 0); } // either compiled value within $timeout, or watch $scope.$watch('result', function(newvalue, oldvalue) { if (newvalue !== undefined) { console.log("do in $timeout or here... " + newvalue); } }); // can access template via template cache if wanted var templatecontent = $templatecache.get('template'); var model = {foo: 'foovalue', bar: 'barvalue'}; var compiledhtml = compilehtmltemplate(templatecontent, model); });
updated plunker: https://plnkr.co/edit/ajc3iqkxpi6o9gfieher?p=preview
Comments
Post a Comment