使用 AngularJS 对包含@attributes的嵌套 JSON 数据进行排序

Sorting nested JSON-data containing @attributes with AngularJS

本文关键字:数据 JSON 排序 嵌套 AngularJS 包含 @attributes 使用      更新时间:2023-09-26

我正在尝试对具有 2 个不同属性、人口和平方英里的嵌套 JSON 数据进行排序。

这是我迄今为止取得的成就。

http://codepen.io/anon/pen/zxooMv

我认为问题出在ng重复@attributes..

<tr ng-repeat="state in data.states.state"['@attributes']"|orderBy:orderByField:reverseSort">

我该如何解决这个问题?

使用该array.map可以投影数据,以便更轻松地处理和删除@attributes属性:

var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'population';
  $scope.reverseSort = false;
  var data = {"states":{
      "state":[{
        "@attributes":{ "name":"ALABAMA","abbreviation":"AL","capital":"Montgomery","most-populous-city":"Birmingham","population":"4708708","square-miles":"52423","time-zone-1":"CST (UTC-6)","time-zone-2":"EST (UTC-5)","dst":"YES"}},{
        "@attributes":{"name":"ALASKA","abbreviation":"AK","capital":"Juneau","most-populous-city":"Anchorage","population":"698473","square-miles":"656425","time-zone-1":"AKST (UTC-09)","time-zone-2":"HST (UTC-10)","dst":"YES"}}]}};
  data.states.state = data.states.state.map(function(value) {
    return value['@attributes'];
  });
  // at this stage the data variable will look like this:
  //{
  //    "states": {
  //        "state": [
  //            {
  //                "name": "ALABAMA",
  //                "abbreviation": "AL",
  //                "capital": "Montgomery",
  //                "most-populous-city": "Birmingham",
  //                "population": "4708708",
  //                "square-miles": "52423",
  //                "time-zone-1": "CST (UTC-6)",
  //                "time-zone-2": "EST (UTC-5)",
  //                "dst": "YES"
  //            },
  //            {
  //                "name": "ALASKA",
  //                "abbreviation": "AK",
  //                "capital": "Juneau",
  //                "most-populous-city": "Anchorage",
  //                "population": "698473",
  //                "square-miles": "656425",
  //                "time-zone-1": "AKST (UTC-09)",
  //                "time-zone-2": "HST (UTC-10)",
  //                "dst": "YES"
  //            }
  //        ]
  //    }
  //}
  $scope.data = data;
});

现在在您看来,您可以简单地使用它:

<tr ng-repeat="state in data.states.state|orderBy:orderByField:reverseSort">