AngularJS在引导表中将文本解析为HTML

AngularJS parse text as HTML in bootstrap table

本文关键字:文本 HTML AngularJS      更新时间:2023-09-26

我想在引导表中显示一些文本。文本应该被解析为HTML,因为我需要<br/> -标签来显示彼此下面的所有不同链接。看到这个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";
});

默认情况下注入到模板中的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在你的模板中呈现它们。

您需要使用消毒模块: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";
});

您可以使用ng-bind-htmlng-bind-html-unsafe来实现这种目的。

示例如下