Sorting of numbers within brackets in angular datatables

拜拜、爱过 提交于 2019-12-06 04:43:18

问题


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:


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>


来源:https://stackoverflow.com/questions/29475966/sorting-of-numbers-within-brackets-in-angular-datatables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!