【问题标题】:AngularJS parse text as HTML in bootstrap tableAngularJS 在引导表中将文本解析为 HTML
【发布时间】:2016-08-11 16:57:26
【问题描述】:

我想在引导表中显示一些文本。由于我需要<br/>-tags 来显示彼此下方的所有不同链接,因此文本应该被解析为 HTML。使用我的代码查看this Plunker。
如您所见,我使用了默认的 ng-bind 指令以及已弃用的 ng-bind-html,但文本要么显示为纯文本,要么根本不显示。
你们能告诉我如何显示解析为 HTML 的文本吗?

这里是我的 HTML 表格的代码:

<table class="table">
  <thead>
    <tr>
      <th>Method</th>
      <th>$scope.other</th>
      <th>$scope.links</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>ng-bind</td>
      <td>{{other}}</td>
      <td>{{links}}</td>
    </tr>
    <tr>
      <td>ng-bind-html</td>
      <td ng-bind-html="other"></td>
      <td ng-bind-html="links"></td>
    </tr>
  </tbody>
</table>

匹配的控制器:

app.controller('TestController', function($scope){
  $scope.links = 'https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/>';

  $scope.other = "sample Text";
});

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    默认情况下,注入模板的 HTML 是不安全的,您必须将其标记为受信任。

    app.controller('TestController', function($scope, $sce){
        $scope.links = $sce.trustAsHtml('https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/>');
    
        $scope.other = "sample Text";
    });
    

    是否有需要直接注入 HTML 的原因?你可以有一个链接的地图/列表,并使用ng-repeat 在你的模板中呈现它们。

    【讨论】:

    • 我试图将所有数据映射到一个数组中,但我不知道如何显示它。我必须测试要显示的数据是简单的字符串还是数组
    • @JohnDizzle Like this 例如?或者你可以有一个数组数组,然后简单地添加另一个嵌套的 ng-repeat。
    • 这个想法看起来不错,但是我的数据在单个对象中,包含字符串和数组,所以我必须先确定下一个属性是哪种数据类型。我需要一种方法来确定我的 HTML 模板中的数据类型
    • @JohnDizzle 那你为什么不在你的服务或控制器中预处理数据呢?统一结构,然后简单地渲染它。您可以将ngRepeat 与数组和对象一起使用。
    • 您能建议一种方法来处理我的数据吗?这是我的另一个问题的链接:stackoverflow.com/questions/38891926/…
    【解决方案2】:

    你需要使用 Sanitize 模块:https://docs.angularjs.org/api/ngSanitize/service/$sanitize

    app.controller('TestController', function($scope, $sce){
      $scope.links = $sce.trustAsHtml('https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/> \
                   https://www.google.com <br/> https://angularjs.org/ <br/>');
    
      $scope.other = "sample Text";
    });
    

    【讨论】:

      【解决方案3】:

      您可以将ng-bind-htmlng-bind-html-unsafe 用于该目的。

      示例显示here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 2022-01-20
        • 1970-01-01
        • 2014-07-18
        • 2017-11-28
        • 2020-12-31
        相关资源
        最近更新 更多