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

uib-popover-html won't accept my html string

我使用的是angular-ui-bootstrap的0.14.2版本。我无法在弹出窗口中显示行 returns。 我使用 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

我使用 $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>

Updated Plunker

或者如果您的内容是动态的并且您需要一个函数:

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>

Plunker

(缓存 trustAsHtml 返回值的原因是 trustAsHtml 总是 returns 一个新对象,因此会导致无限 $digest 循环)

公认的方法很容易导致您的应用程序中出现跨站点脚本漏洞。如果您明确信任要显示的内容,您实际上应该只使用 $sce.trustAsHtml。 angular-bootstrap 文档也暗示:

The user is responsible for ensuring the content is safe to put into the 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