gpt4 book ai didi

javascript - AngularJS orderby 整数字段无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 02:29:56 24 4
gpt4 key购买 nike

我只是从 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 正常工作。

添加到您的 Controller 以将 String age 排序为 float:

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

应该可以,

参见 PLunker

关于javascript - AngularJS orderby 整数字段无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com