javascript - 通过使用 angularjs ngtable 单击标题使表格标题可排序

标签 javascript html angularjs ngtable

我正在使用 angularjs ng-table 模块。我想通过单击标题来对表格进行排序。这是相关的html代码。

<div ng-controller="ViewCtrl" class="container">
    <table ng-table="tableParams" class="table table-bordered">
        <thead>

        <tr>
            <th>name</th>            
            <th>changeInPercent</th>
            <th>Ratio</th>
        </tr>

        <thead>
        <tbody>
        <tr ng-repeat="stk in $data">
            <td data-title="'name'" filter="{ name: 'text'}" sortable="'name'" " >
                {{stk.name}}
            </td>
            <td data-title="'changeInPercent'" >
                {{stk.changeInPercent}}
            </td>
            <td data-title="'Ratio'" >
                {{stk.Ratio}}
            </td>
        </tr>
        </tbody>
    </table>
</div>

相关 Controller 代码如下所示;

.controller('ViewCtrl', ['$scope', '$http', 'configuration', 'ngTableParams',
    function ($scope, $http, $configuration, ngTableParams) {
        var tableData = [];
        //Table configuration
        $scope.tableParams = new ngTableParams({
            page: 1,
            count: 100
        }, {
            total: tableData.length,
            //Returns the data for rendering
            getData: function ($defer, params) {                    
                var url = $configuration.webroot + '/fsa/list?list=XXlist';
                $http.get(url).then(function (response) {
                    tableData = response.data;
                    $defer.resolve(tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    params.total(tableData.length);
                });
            }
        });
    }])

表格数据显示正确。我希望名称列可以通过单击进行排序。但是,名称列仍然无法排序。代码有什么问题?

最佳答案

终于明白了!

只需删除 thead 元素即可。它将使用您在 data-title 属性中提到的标题自动构建。

编辑:这里是 JsFiddle 。您可能需要在 getData 中添加一些处理,如以下代码段所示:

$scope.tableParams = new ngTableParams({
  // ...
}, {
  // ...
  getData: function($defer, params) {
    // apply sorting and such 
    $scope.tableData = params.sorting() ? $filter('orderBy')($scope.tableData, params.orderBy()) : $scope.tableData;
    $scope.tableData = params.filter() ? $filter('filter')($scope.tableData, params.filter()) : $scope.tableData;
    $scope.tableData = $scope.tableData.slice((params.page() - 1) * params.count(), params.page() * params.count());
    $defer.resolve($scope.tableData);
  }
});

希望这有帮助。

关于javascript - 通过使用 angularjs ngtable 单击标题使表格标题可排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34963090/

相关文章:

css - 如何在 radio 旁边放置文本区域和文本输入?

html - 链接不适用于 Logo

angularjs - angular-ui-router 嵌套状态不适用于多个 View

javascript - 使用 angular.js ui-router 单击链接时出错

javascript - Vue 无法呈现具有父级的数据对象

javascript - 具有部分提供的属性的 JSX 元素文字

javascript - 将 jQuery 代码转换为 Polymer?

html - 在 asp.core razor 页面中设置所选项目

javascript - 3个大写字母的正则表达式,不多也不少

angularjs - 如何在按钮单击时传递表单操作以及在该按钮单击时执行某些功能?