我有此数据:
[{"id":"42","firstname":"Sarah","lastname":"Dilby","age":"40","cars":"Yaris"}, {"firstname":"Jason","lastname":"Diry","age":"5","id":"5"}, {"id":"6","firstname":"Bilson","lastname":"Berby","age":"1","cars":"Tipo"}]
当我通过ng- repeat按id或按年龄排序时,它会将数字排序为文本。由于我找不到它写的任何地方的问题,所以我猜我的代码有问题。我创建了这个小提琴:http : //jsfiddle.net/vsbGH/1/很抱歉,该模板,但jsfiddle不允许在html框中使用。无论如何,这是加载和排序数据的代码:
//user data app.service('People', function() { var People = {}; People.details = [{"id":"42","firstname":"Sarah","lastname":"Dilby","age":"40","cars":"Yaris"}, {"firstname":"Jason","lastname":"Diry","age":"5","id":"5"}, {"id":"6","firstname":"Bilson","lastname":"Berby","age":"1","cars":"Tipo"}] return People; }); //list ctrl controllers.listCtrl = function ($scope,People) { $scope.people = People.details; $scope.sortList = function(sortname) { $scope.sorter = sortname; } }
这是模板的ng-repeat部分:
<tr ng-repeat="person in people | orderBy:sorter "> <td>{{person.id | number}}</td> <td>{{person.firstname}} </td> <td>{{person.lastname}} </td> <td>{{person.age | number}}</td> <td>{{person.cars}} </td> </tr>
非常感谢您能帮助我理解为什么数字数据不按数字排序以及为什么不按文本排序。
我认为最合适的解决方案是正确格式化JSON对象上的数字,即不要将其用引号引起来。所以:
变成:
[{"id":42,"firstname":"Sarah","lastname":"Dilby","age":40,"cars":"Yaris"}, {"firstname":"Jason","lastname":"Diry","age":5,"id":5}, {"id":6,"firstname":"Bilson","lastname":"Berby","age":1,"cars":"Tipo"}]
我猜想SergL的解决方案是好的,如果不可能更正JSON数据的格式。
除此之外,在我的特定情况下,问题与服务器端PHP的json_encode函数有关。默认情况下,它将数字视为字符串。要修复,我必须JSON_NUMERIC_CHECK在PHP脚本中将选项添加到encode方法:
JSON_NUMERIC_CHECK
json_encode($assoc_array,JSON_NUMERIC_CHECK);