我使用了角度ui-bootstrap的0.14.2版本。我无法在弹出窗口中显示行返回。 我使用popover-html指令和一个字符串,如
Limite inférieure<br>Limite supérieure
它出现以下错误:
Lexer Error: Unexpected next character at columns 41-41 [é] in expression [<div>Approchant des limites<br>Limite supérieure: 34:12<br>Limite inférieure: -34:12</div>].
我尝试在$ sce.trustAsHtml调用中包装我的字符串,但它没有改变。
答案 0 :(得分:18)
使用$sce.trustAsHtml
为我工作,如下所示。
注意:trustAsHtml
告诉Angular相信HTML是安全的,所以只有在你信任HTML时才使用它,即它不是用户提供的。
JS:
$scope.popoverContent = $sce.trustAsHtml('Line 1<br>Line2');
HTML:
<button popover-placement="right" uib-popover-html="popoverContent" type="button" class="btn btn-default">Popover</button>
或者,如果您的内容是动态的,并且您需要一个功能:
JS:
$scope.input = 'Line 1<br/>Line 2';
var trusted = {};
$scope.getPopoverContent = function(content) {
return trusted[content] || (trusted[content] = $sce.trustAsHtml(content));
}
HTML:
<button popover-placement="right" uib-popover-html="getPopoverContent(input)" type="button" class="btn btn-default">Popover</button>
(缓存trustAsHtml
返回的值的原因是trustAsHtml
总是返回一个新对象,因此可能导致无限$ digest循环)
答案 1 :(得分:3)
接受的方法很容易导致应用程序中的跨站点脚本漏洞。如果您明确信任要显示的内容,则应该只使用$sce.trustAsHtml
。 angular-bootstrap文档也提示:
用户有责任确保将内容安全放入DOM中!
另一种更安全的方法是将uib-popover-template
与简单模板结合使用,ng-bind-html
自动使用$sanitize
来清理HTML。
<强> HTML 强>
<p uib-popover-template="myPopoverTemplateUrl"
popover-trigger="mouseenter"
popover-placement="top"
popover-append-to-body="true">
Show a Popover on Hover
</p>
<script type="text/ng-template" id="myPopoverTemplate.html">
<div>
<p ng-bind-html="popoverContent"></p>
</div>
</script>
<强> JS 强>
$scope.myPopoverTemplateUrl = "myPopoverTemplate.html";
$scope.popoverContent = "This is HTML <b> And will be sanitized."
您还需要确保在应用中声明ngSanitize
并添加angular-sanitize.js
脚本。请查看更新的plunker以供参考。