Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I'm trying to sort nested JSON-data with 2 different attributes, population and squaremiles.

Here's what i have achieved so far.

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

I think the problem is with ng-repeat @attributes..

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

How do i solve this?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Using the array.map you could project your data so that it is easier to work with and get rid of the @attributes property:

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;
});

Now in your view you could simply use that:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.