【发布时间】:2017-04-07 10:55:20
【问题描述】:
在我的 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 指令。
【问题讨论】:
-
想发明轮子?或者你想得到什么?正如您在上一个问题中所评论的那样,您可能想要 $interpolate 而不是 $compile。
-
编译后需要对值进行$eval
-
@PetrAveryanov
$interpolate不起作用,因为模板包含指令 -
@blackmiaool
foo有一个值,所以ng-if评估为真。 -
@estus OP 并没有说这不是一个有用的、有效的问题。只是他们不想进一步解释。这完全是他们的特权。一方面,细节可能具有商业敏感性。此外,在 100k 时,他们已经存在足够长的时间,可以在后台拥有一定程度的经验。
标签: javascript angularjs