json 对象列表排序使用 angular js 中的 id 列

json object list sort using id column in angular js

我需要在呈现浏览器之前对 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;

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

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

在你的html

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

这将使您的 collections 按 id

排序