在你的 Plunker 中你正在使用ng-bind-html
它不会为您编译 HTML。您可以创建一个新指令来为您执行此操作。
源代码为ng-bind-html
:
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBindHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-evaluate the expr because we want a TrustedValueHolderType
// for $sce, not a string
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
});
};
}
};
}];
为新指令选择一个名称,例如compile-html
.
Replace tAttrs.ngBindHtml
with tAttrs.compileHtml
(或您选择的任何名称)。
你需要更换$sce.getTrustedHtml
with $sce.trustAsHtml
,否则你会得到Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.
然后你需要打电话$compile
:
$compile(element.contents())(scope);
完整指令:
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);
});
};
}
};
}
]);
Usage:
<div compile-html="tab.content"></div>
Demo: http://plnkr.co/edit/TRYAaxeEPMTAay6rqEXp?p=preview http://plnkr.co/edit/TRYAaxeEPMTAay6rqEXp?p=preview