角度数据表中括号内的数字排序 [英] Sorting of numbers within brackets in angular datatables
问题描述
我使用 Angular数据表根据网络服务响应填充我的表格。我的网络服务给我一个json,如下所示
I am using Angular datatables to populate my table based on a webservice response. My webservice returns me a json like below
[
{
"id": 1,
"name" : "abc",
"count": "(20)"
},
{
"id": 2,
"name" : "abc2",
"count": "20"
},
{
"id": 3,
"name" : "abc3",
"count": "(30)"
}
]
我能够将JSON数组绑定到下表中的$ scope变量
I am able to bind the JSON array to my $scope variable in the table below
<table datatable="ng" dt-options="dtOptions" dt-column-defs="dtColumnDefs">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>count</th>
</tr>
</thead>
<tbody ng-repeat= "item in items">
<td> {{item.id}} </td>
<td> {{item.name}} </td>
<td> {{item.count}} </td>
</tbody>
</table>
id 和名称列已排序正确地按升序和降序排列,但计数列不会根据数字排序。相反,在排序和排序时需要考虑()。我希望计数列的排序结果为
The id and name columns are sorted properly in ascending and descending order but the count column is not sorted based on the numbers. Instead it takes the "(" into account while sorting and the sorting. I want the sort result for the count column to be
升序
20
(20)
(30)
现在我按升序排列
(20)
(30)
20
任何人都可以建议我需要申请的逻辑是什么?
Can anyone suggest what is the logic i need to apply?
推荐答案
您可以使用列呈现功能。当dataTables需要计数值
时列,并希望使用该值 sort
该列,然后传回包含列数据的数字部分的类型号:
You can use a column render function. When ever dataTables need values for the count
column, and want to use the value to sort
the column, then pass back a typed number containing the number part of the column data :
$scope.dtColumnDefs = [
DTColumnDefBuilder
.newColumnDef(2)
.withOption('type', 'number')
.renderWith(function(data, type, full) {
if (type == 'sort') {
var value = data.match(/\d+/);
if (value == null) {
return 0
} else {
value = parseFloat(value[0]);
}
return value.toString().length != data.length ? value+0.0001 : value;
}
return data
})
];
这里我将 0.0001
添加到包含的值非法字符,例如(
- 通过我们可以确定值以正确的顺序显示,即所有 20
是所有(20)
之前(或之后)将组合在一起。
Here I add 0.0001
to values that contain illegal characters, like (
- by that we can be sure values is displayed in the correct order, i.e all 20
is grouped together before (or after) all (20)
.
demo - > http://plnkr.co/edit/Zyp0yphHfxnElEjMMOh2?p=preview
demo -> http://plnkr.co/edit/Zyp0yphHfxnElEjMMOh2?p=preview
注意:我会迭代< tr>
的,不是< tbody>
:
NB: I would iterate over the <tr>
's, not <tbody>
:
<tbody>
<tr ng-repeat="item in items">
<td> {{item.id}} </td>
<td> {{item.name}} </td>
<td> {{item.count}} </td>
</tr>
</tbody>
这篇关于角度数据表中括号内的数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!