首页 > 解决方案 > json对象列表使用角度js中的id列排序

问题描述

在渲染浏览器之前,我需要对我的 json 数据对象进行排序。这是我的 json 格式

$scope.cityData= [
    {
        id: '520',
        city:'col01'
    },
    {
        id: '410',
        city:'col02'
    },
    {
        id: '412',
       city:'col03'
    }]

我试着去做。但我的代码有问题。我控制台记录它。但没有排序

$scope.cityData.sort(function (a, b) { return a.id - b.id });
console.log($scope.cityData); 
$scope.newCitySort = $scope.cityData;

我还需要将此排序数据分配给新的范围变量。我该怎么做?

标签: javascriptangularjs

解决方案


如果您不需要对实际的 $scope.cityData 进行排序。您可以只使用orderBy过滤器

在你的 html

<ul ng-repeat="city in cityData | orderBy: 'id' ">
  <li>**your list rendering code here**</li>
</ul>

这将使您的收藏品按 id 排序


推荐阅读