You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular DataTables无法渲染HTML:表格与Modal仅显纯文本求助

解决Angular DataTables与Bootstrap Modal中HTML标签无法渲染的问题

一、Bootstrap Modal内HTML渲染修复

Angular默认会对插值表达式{{}}的内容做HTML转义,导致带标签的字段显示纯文本。需通过ng-bind-html配合$sce服务处理:

  1. 控制器中注入$sce并添加信任HTML的函数:
app.controller('crudController', function($scope, $http, $sce) {
  // 新增:信任HTML内容的工具函数
  $scope.trustAsHtml = function(html) {
    return $sce.trustAsHtml(html);
  };

  // 原有业务代码保持不变
  $scope.success = false;
  $scope.error = false;

  $scope.viewModal = function(id) {
    var modal_popup = angular.element('#crudmodalx');
    modal_popup.modal('show');
  };

  $scope.viewData = function(id) {
    $http({
      method: "POST",
      url: "view.php",
      data: {
        'id': id,
        'action': 'viewData'
      }
    }).success(function(data) {
      $scope.namesView = data;
      $scope.viewModal();
    });
  };
});
  1. 修改Modal中带HTML字段的绑定方式,替换原插值表达式:
<div class="card text-white bg-primary mb-3">
  <div class="card-header">Known Expertise:</div>
  <div class="card-body">
    <p class="card-text" ng-bind-html="trustAsHtml(name.known_expertise)"></p>
  </div>
</div>
<div class="card text-white bg-danger mb-3">
  <div class="card-header">Restrictions: </div>
  <div class="card-body">
    <p class="card-text" ng-bind-html="trustAsHtml(name.other_restrictions)"></p>
  </div>
</div>

二、Angular DataTables中HTML渲染修复

针对DataTables列内的HTML内容,有两种处理方式:

方式1:列定义中使用render函数

在DataTables初始化的列配置里,指定带HTML字段直接返回原始内容:

$scope.dtOptions = DTOptionsBuilder.newOptions()
  .withOption('ajax', 'your-data-source.php')
  .withColumns([
    { data: 'agent' },
    { data: 'facility' },
    // 处理带HTML的字段
    { 
      data: 'known_expertise',
      render: function(data) {
        return data; // 不转义,直接渲染HTML
      }
    },
    { data: 'other_restrictions' },
    { 
      data: null,
      defaultContent: '<button ng-click="viewData(id)">View</button>'
    }
  ]);

方式2:使用ng-bind-html指令(适用于ng-repeat渲染的表格)

如果表格通过ng-repeat生成,直接在单元格中使用指令:

<table datatable="ng" dt-options="dtOptions">
  <thead>
    <tr>
      <th>Agent</th>
      <th>Known Expertise</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="item in dtData">
      <td>{{item.agent}}</td>
      <td ng-bind-html="trustAsHtml(item.known_expertise)"></td>
    </tr>
  </tbody>
</table>

注意事项

  • 确保后端返回的HTML内容安全,若来自用户输入需做XSS过滤处理。
  • AngularJS 1.6+版本默认启用$sce安全机制,必须显式信任HTML才能渲染。

内容的提问来源于stack exchange,提问作者Mohamed El Habchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:55:18