我的代码使用ng-repeat将html代码绑定到div,如此
<div ng-repeat="item in items" ng-bind-html="item.html">
在传入的html代码中,我想添加一个带有ng-repeat指令的表,以便在从单独的Web服务返回时可以使用数据填充它。 items.item中的html看起来像:
<table>
<tr ng-repeat=\"person in people\">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</table>
目前我的输出看起来像
{{person.id}} {{person.firstName}} {{person.lastName}}
有什么建议可以让它发挥作用吗?
答案 0 :(得分:2)
ng-bind-html
不会为您编译内容。
您可以使用此指令,该指令基于ng-bind-html
的源代码,但已修改为也可编译:
app.directive('compileHtml', ['$sce', '$parse', '$compile',
function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.compileHtml);
var ngBindHtmlWatch = $parse(tAttrs.compileHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.compileHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
element.html($sce.trustAsHtml(ngBindHtmlGetter(scope)) || '');
$compile(element.contents())(scope);
});
};
}
};
}
]);
用法:
<div ng-repeat="item in items" compile-html="item.html">
答案 1 :(得分:1)
您必须先使用$compile
服务编译您的html。你可以查看文档。