【问题标题】:uib-popover-html won't accept my html stringuib-popover-html 不接受我的 html 字符串
【发布时间】:2016-08-29 19:01:20
【问题描述】:

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

【问题讨论】:

    标签: angularjs angular-ui-bootstrap


    【解决方案1】:

    使用$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总是返回一个新对象所以会导致无限的$digest循环)

    【讨论】:

    • 谢谢。这很好用,但我不明白语法。为什么这不起作用? $scope.getPopoverContent = function(input) { var content = input;返回 $sce.trustAsHtml(content)); }
    • 这是因为这个问题和解决方法在这里github.com/angular/angular.js/issues/3932
    • 如果显示用户提交的输入,此解决方案可能会导致跨站点脚本。
    • 还有内存泄漏,因为“可信”对象会越来越膨胀
    【解决方案2】:

    公认的方法很容易导致您的应用程序中存在跨站点脚本漏洞。如果您明确信任要显示的内容,您应该只使用$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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      • 2019-02-17
      • 1970-01-01
      • 2014-04-12
      • 2013-02-23
      相关资源
      最近更新 更多