[英]Sorting number field in Angular
I have a table of data being populated by Angular but the 'rate' field is sorting as if it were a string and not a number. 我有一个由Angular填充的数据表,但是'rate'字段正在排序,就好像它是一个字符串而不是一个数字。 I know it needs converting but am not sure how to do it, especially as the list is being populated via AJAX. 我知道它需要转换,但不确定如何执行,尤其是通过AJAX填充列表时。
Angular 角度的
app.controller('itemsCrtl', function ($scope, $http, $timeout) {
function returnItems(f){
$http.get('angular-ajax/vcodes.php?filter=' + f).success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 50; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
}
$scope.changeFilter = returnItems; // provide function for button click
returnItems('all'); // initialize default filter (all contacts)
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
Table with column sort headers 具有列排序标题的表
<table>
<thead>
<th>Code <a ng-click="sort_by('code');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Description <a ng-click="sort_by('description');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Rate % <a ng-click="sort_by('rate');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in filtered = (list | orderBy : predicate :reverse)">
<td>{{data.code | decodeURI}}</td>
<td>{{data.description | decodeURI}}</td>
<td>{{data.rate | number:2}}</td>
</tr>
</tbody>
</table>
The orderBy documentation says: orderBy 文档说:
Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings. 注意:如果您发现数字未按预期进行排序,请确保将其实际保存为数字而不是字符串。
So, not having access to your dataset I assume that's the problem. 因此,我无法访问您的数据集,我认为这就是问题所在。 If you can't control the data in the API, then you could process it in your http get return function: 如果您无法控制API中的数据,则可以在http get返回函数中对其进行处理:
$http.get('angular-ajax/vcodes.php?filter=' + f).success(function(data){
$scope.list = data;
$scope.list.forEach(function(item, index){
$scope.list[index].rate = Number(item.rate);
});
. . .
});
Depending how much confidence you have in the rate field only being numbers or number-strings you could introduce error handling in the loop 取决于您对码率字段只有多少数字或数字字符串的信心,您可以在循环中引入错误处理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.