如何制作 table sort-able 而整个组件通过 AngularJS 中的 ng-bind-html 作为字符串传递

How to make a table sort-able while the whole components is passed as string via ng-bind-html in AngluarJS

你好,我在 AngluarJS 中有一个情况,HTML 是由 back-end 生成的,front-end 唯一应该做的就是把 HTML大多数 table 标签到 ng-bind-html 中并显示给用户。但是现在这些 table 也应该是 sort-able。我该怎么做?

我已经完成的事情是使用 this 创建我自己的指令,因此使静态字符串 HTML 也采取一些操作。但是对它们进行排序是另一回事。换句话说,我想让我完全生成的 table 和所有 <tr><td> 按我的操作排序。

这是我的简化代码(compile 是我的指令):

JS:
// The string is fully generated by back-end
$scope.data.html = 
'<table> <tr> <th ng-click="sortByHeader($event)"> Name </th> 
              <th ng-click="sortByHeader($event)"> Age </th> </tr>
              <tr> <td> Sara </td> <td> 15 </td> </tr>
              <tr> <td> David </td> <td> 20 </td> </tr>'

HTML: 
<div compile="data.html"></div>

ng-click="sortByHeader($event) 是 back-end 可以为我准备的东西,所以我可以使用它,多亏了我写的 compile 让我找出哪个 header 有被点击。除此之外,我无能为力。除非你能帮助我 :D

在此先感谢,我希望我的问题很清楚。

问题“渲染的 table 是否必须与后端检索的 HTML 完全匹配?”的答案是一种“ 没有"?

如果是这种情况,那么这里有一种通过使用正则表达式从后端 HTML 字符串解析和捕获内容来获得对 table 内容的控制的 hacky 方法。

例如:抓取所有行数据并在客户端应用排序

// Variables to be set by your sortByHeader functions in order to do client-side sorting
$scope.expression = null;
$scope.direction = null;

var regexToGetTableHead = /<table>\s*(.*<\/th>\s*<\/tr>)/g;
$scope.tableHead = regexToGetTableHead.exec($scope.data.html);

$scope.tableRows = [];

var regexToGetRowContents = /<tr>\s*<td>\s*(\w*)\s*<\/td>\s*<td>\s*(\w*)\s*<\/td>\s*<\/tr>/g;

var match;
while ((match = regexToGetRowContents.exec($scope.data.html)) != null) {
    $scope.tableRows.push({
        "name": match[1],
        "age": match[2] 
    });
}

和HTML

<table>
    <thead compile="tableHead"></thead>

    <tbody>
        <tr ng-repeat="row in tableRows | orderBy: expression : direction">
            <td>{{row.name}}</td>
            <td>{{row.age}}</td>
        </tr>
    </tbody>
</table>

由于您用 sorttable.js 标记了您的问题,我假设您正在使用该脚本对 table 进行排序。 现在,如果我理解正确的话,sorttable.js 会用 class sortable 解析任何 table 的 HTML。您的 table 显然是动态加载的,因此 sorttable.js 在解析 HTML.

时不知道它

但是你也可以告诉它动态添加 table sortable。

相关部分摘自以下页面: https://kryogenix.org/code/browser/sorttable/#ajaxtables

Sorting a table added after page load

Once you've added a new table to the page at runtime (for example, by doing an Ajax request to get the content, or by dynamically creating it with JavaScript), get a reference to it (possibly with var newTableObject = document.getElementById(idOfTheTableIJustAdded) or similar), then do this:

sorttable.makeSortable(newTableObject);

你应该可以用 angular 做到这一点。如果没有,我可以稍后尝试整理一些东西。