javascriptangularjssmart-table

How to sort by smaller Numbers to Larger Numbers in smart table?


The following is my code, When user clicks the th title ID it will sort by ID number
(1->2->3->-11->23)
but the result is (1->11->2->23->3)
I hope the result is sort by smaller Numbers to Larger Numbers or Larger Numbers to smaller Numbers.....I don't want to add zero in single number.....

<div class='container' ng-app='smarttabledemo' ng-controller='smarttabledemo'>
      <h3>Smart-Table</h3>
      <table st-table='data' class='table'>
        <thead>
          <tr>
            <th st-sort='ID'>ID</th>
            <th st-sort='firstName'>First Name</th>
            <th st-sort='lastName'>Last Name</th>
            <th st-sort='phone'>Phone Number</th>
            <th st-sort='hometown'>Hometown</th>
          </tr>
        </thead>
        <tbody>
          <tr st-select-row='row' ng-repeat='row in data'>
          <td>{{row.ID}}</td>
            <td>{{row.firstName}}</td>
            <td>{{row.lastName}}</td>
            <td>{{row.phone}}</td>
            <td>{{row.hometown}}</td>
          </tr>
        </tbody>
      </table>

    </div>

my json file

  $scope.data = [
    { ID: '3',firstName: 'Sam', lastName: 'Evans', phone: 'Not Provide', hometown: 'Anytown, ST' },
    { ID: '23',firstName: 'Saul', lastName: 'Evans', phone: '555-555-1234', hometown: 'Anytown, ST' },
    { ID: '1',firstName: 'Charlie', lastName: 'Anders', phone: '555-555-9876', hometown: 'Springfield, ST' },
    { ID: '2',firstName: 'Jessica', lastName: 'Cortez', phone: 'Not Provide', hometown: 'Springfield, ST' },
    { ID: '11',firstName: 'Amy', lastName: 'Wood', phone: '555-555-1348', hometown: 'Metroville, ST' },
  ]

enter image description here

The following is my fiddle demo, Thanks
Fiddle


Solution

  • The problem is your ID is a string so it's sorting alpha and not numerically.

    Change all the ID to a number, or if you don't want to do the work, insert this after you assign the array:

    $scope.data.forEach(o=>o.ID=+o.ID)
    

    https://jsfiddle.net/qwc5s6qt/6/

    Otherwise, update the data or your Angular getter for a custom sort function.