Sorting of numbers within brackets in angular data

2019-04-10 14:00发布

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)"
 }
] 

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>

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

In ascending

20

(20)

(30)

Right now i get in ascending order

(20)

(30)

20

Can anyone suggest what is the logic i need to apply?

1条回答
祖国的老花朵
2楼-- · 2019-04-10 14:36

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              
    })
]; 

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


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>
查看更多
登录 后发表回答