在我的 Angular 1.5.11 应用程序中,我尝试以编程方式编译模板并将结果作为 HTML 字符串获取。模板内容为
<div ng-if="foo">
<div>foo is {{foo}}, bar is {{bar}}</div>
</div>
我尝试将其编译为 HTML 字符串:
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;
});
但是,正如您在此 Plunker example 中看到的那样, 它不起作用。我需要编译模板而不只是对其进行插值,因为它包含一个 ng-if
指令。
最佳答案
Angular 的摘要循环需要先完成,然后您才能访问该值。您可以通过使用 $timeout
来实现。
我使用 $templateCache
来检索模板,因为这是官方方式,但这只是个人喜好。
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 now completed:', parent[0].innerHTML);
$scope.result = parent[0].innerHTML;
}, 0);
}
// either do something with the compiled value within the $timeout, or watch for it
$scope.$watch('result', function(newValue, oldValue) {
if (newValue !== undefined) {
console.log("Do something in the $timeout or here... " + newValue);
}
});
// you can access the template via the template cache if you wanted
var templateContent = $templateCache.get('template');
var model = {foo: 'fooValue', bar: 'barValue'};
var compiledHtml = compileHtmlTemplate(templateContent, model);
});
更新的 Plunker:https://plnkr.co/edit/ajC3Iqkxpi6O9gfieHeR?p=preview
关于javascript - 以编程方式将 Angular 模板编译为 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43276380/