Trying to keep the code as minimal as possible (avoiding writing a sort function). I have a simple table of data that is sortable.

The issue in this example is that "score" does not sort numerically. The user 'Julie' has the lowest score of '9.12' however when sorted it appears to be doing so lexically.

The example is a modified version of the example used in the angular docs on orderby

Here is a snippet of the code and associated plunker.

<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  <hr/>
  <table class="user">
    <tr>
      <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
          (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
      <th><a href="" ng-click="predicate = 'score'; reverse=!reverse">user score</a></th>
      <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
    </tr>
    <tr ng-repeat="user in users | orderBy:predicate:reverse">
      <td>{{user.name}}</td>
      <td>{{user.score}}</td>
      <td>{{user.age}}</td>
    </tr>
  </table>

http://plnkr.co/edit/Ytpj3SUgtLKQvQvB4Yhb

有帮助吗?

解决方案

The issue is that your score attribute in your data structure is a string. You can:

A) change it to be a number score:9.12 instead of score:'9.12' http://plnkr.co/edit/YItGeFfFLN8OnXeejv7m?p=preview

B) If you can't change the data, write a function ("Getter function. The result of this function will be sorted using the <, =, > operator") for the expression portion of your orderBy that'll return the string to a number for the comparison. <tr ng-repeat="user in users | orderBy:yourfunction:reverse">

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top