2016-02-04 60 views
0

我有一个由Angular填充的数据表,但'rate'字段按照它是字符串而不是数字进行排序。我知道它需要转换,但不知道如何去做,特别是当列表正在通过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> 
    <thead> 
     <th>Code&nbsp;<a ng-click="sort_by('code');"><i class="glyphicon glyphicon-sort"></i></a></th> 
     <th>Description&nbsp;<a ng-click="sort_by('description');"><i class="glyphicon glyphicon-sort"></i></a></th> 
     <th>Rate % &nbsp;<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> 

回答

0

的排序依据documentation说:

注:如果您注意到如预期的数字没有被排序,确保他们实际上被保存为数字而不是字符串。

因此,无法访问您的数据集我认为这是问题所在。如果你不能在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); 
    }); 
    . . . 
}); 

取决于你有多少信心在速度场仅是号码或号码串你可以在循环中引入错误处理

+0

感谢您的提供,表中的费率列现在显示NaN。 MySql字段是十进制到2位小数(存储为)。如果需要,我可以更改设置。 – Rob

+0

哎呀 - 它应该是'Number(item.rate)'。我会更新我的答案并尝试。 – cstricklan

+0

奇妙的是,这是做的伎俩!非常感谢。 – Rob