AngularJS 按整数字段排序无法正常工作

AngularJS orderby integer field not working properly

本文关键字:常工作 工作 整数 数字段 排序 AngularJS      更新时间:2023-09-26

我刚刚从 http://docs.angularjs.org/api/ng.filter:orderBy 中获取了最简单的演示,只需更改年龄的值以具有不同的位数。它停止按预期工作。它的排序像"字符串"而不是"整数"值。我应该如何更改它,以便它像整数值一样按年龄排序?

Plunkr演示在这里http://plnkr.co/edit/pzgiIYrki7jUZdVaTMt9?p=preview

代码是:

function Ctrl($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:'2352345'},
       {name:'Mary', phone:'555-9876', age:'4235243'},
       {name:'Mike', phone:'555-4321', age:'241'},
       {name:'Adam', phone:'555-5678', age:'34325'},
       {name:'Julie', phone:'555-8765', age:'1234'}]
  $scope.predicate = '-age';
}

<!doctype html>
<html ng-app="App">
  <head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
  <body>
<div ng-controller="Ctrl">
  <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  <hr/>
  [ <a href="" ng-click="predicate=''">unsorted</a> ]
  <table class="friend">
    <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 = 'phone'; reverse=!reverse">Phone Number</a></th>
      <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
    </tr>
    <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
      <td>{{friend.name}}</td>
      <td>{{friend.phone}}</td>
      <td>{{friend.age}}</td>
    </tr>
  </table>
</div>

  </body>
</html>

您必须将年龄转换为数字类型,以使orderBy正常工作。

添加到控制器以将字符串年龄排序为浮点数:

   angular.forEach($scope.friends, function (friend) {
    friend.age = parseFloat(friend.age);
   });

它应该工作,

普伦克

我知道这个答案有点晚了,但是在最新版本的Angular中,您可以使用函数作为orderBy的谓词(https://docs.angularjs.org/api/ng/filter/orderBy)。在这种情况下,向控制器添加一个类似于 next 的函数

$scope.orderByFunction = function(friend){
    return parseInt(friend.age);
};

并更改顺序中的谓词 By 过滤器

ng-repeat="friend in friends | orderBy:orderByFunction:reverse"

这将解决问题!

你只需要删除年龄变量中的引号,因为它是一个整数,而不是一个字符串:

  $scope.friends =
      [{name:'John', phone:'555-1212', age:2352345},
       {name:'Mary', phone:'555-9876', age:4235243},
       {name:'Mike', phone:'555-4321', age:241},
       {name:'Adam', phone:'555-5678', age:34325},
       {name:'Julie', phone:'555-8765', age:1234}]

AngularJ 具有对值进行排序的内置功能。但是在对浮点值进行排序之前,我们需要使用 parseFloat() javavscript 函数将值转换为浮点数。

http://hubpages.com/technology/How-to-sort-table-content-filter-table-data-and-add-pagination-using-Angular-JS

将谓词更改为以下内容也可以:

<th><a href="" ng-click="predicate = '1*age'; reverse=!reverse">Age</a></th>

在将数组转换为 JSON 时添加JSON_NUMERIC_CHECK代码。json_encode($anyarray,JSON_NUMERIC_CHECK);