angularJS 过滤器 "orderBy" 无法对 3 位以上的数字进行排序

angularJS filter "orderBy" fails to sort 3+ digits numbers

我正在尝试将 table 中的整数从小到大排序,但 3 位以上的数字排在 table 的底部。

我从 mysql table 中获取数据并使用角度过滤器 "orderBy" 在 table 中对其进行排序,如下所示:

<table class="table table-hover">
    <thead>
    <td>name</td>
    <td>score</td>
    <td>diff</td>
    </thead>
    <tr ng-repeat="x in names | orderBy: '-score'">
        <td >{{x.name}}</td>
        <td >{{x.score}}</td>
        <td>{{(maxScore(names)-x.score)}}</td>
    </tr>
</table>

maxScore(names) 简单地找到 names 数组中的最大得分值 returns 它:

JS:

$scope.maxScore = function(names){
    var max;
    for (var i = 0; i < names.length; i++) {
        if (names[i].score > (max || 0))
            max = names[i].score;
    }
    return max;
}

table 有 3 列(id、姓名、分数),分数字段包含整数。

排序非常适合 2 位数字,但如果 names[i].score 中的数字是 1 位或 3 位以上,则排序失败 - 每个 3 位以上的数字都会排到 table 而不是顶部。所有 2 位数字都按预期从大到 small.can 排序,有人帮我弄清楚为什么吗?

我不知道具体哪里出了问题,但是 I cleaned up your code in a codepen 一切似乎都正常。

<!-- markup -->
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Score</th>
      <th>Diff</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="player in players | orderBy:'-score'">
      <td>{{player.name}}</td>
      <td>{{player.score}}</td>
      <td>{{maxScore() - player.score}}
    </tr>
    <tr>
  </tbody>
</table>

// JS
function ctrl ($scope) {
  $scope.players = [
    // fake data with different digit scores
  ]

  $scope.maxScore = function() {
    var max;
    angular.forEach($scope.players, function(player) {
      if (player.score > (max || 0))
        max = player.score;
    });
    return max;
  }
}

也许您实际上不是在处理数字而是一串数字,您应该先 parseInt

ranks in ranking | orderBy:max:'amount'

在 ng-repeat 中试试这个,这将有助于按最大值排序数据。

<div ng-controller="ExampleController">
  <table class="friends">
    <tr>
      <th>Name</th>
      <th>Phone Number</th>
      <th>Age</th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:'-age'">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>
</div>

You can always follow the docs