uib-popover-html不接受我的html字符串

时间:2015-10-23 07:57:52

标签: angularjs angular-ui-bootstrap

我使用了角度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调用中包装我的字符串,但它没有改变。

这是一个掠夺者 http://plnkr.co/edit/3JSly1anPBUiGyqBcsD1

2 个答案:

答案 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>

SqlFiddleDemo

或者,如果您的内容是动态的,并且您需要一个功能:

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>

Updated Plunker

(缓存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以供参考。

Updated Plunker