0

I have an object which keys are years:

years: {
  "2100": {
    countingAgent: false,
    turns: 3,
    cards: 4,
    score: 3
  },
  "2000": {
    countingAgent: false,
    turns: 4,
    cards: 3,
    score: 4
  },
  "1900": {
    countingAgent: false,
    turns: 5,
    cards: 2,
    score: 6
  } ... 
}

I want the higher years to be first, I have this ng-repeat:

<li class="year" ng-repeat="(year, data) in years">

I tried | orderBy:'year':true" and | orderBy:'score':true" but none worked, it always puts 1900 first.

---UPDATE---

It seems all solution resolve around creating a filter converting object to array. Is there no solution that is more elegant?

ilyo
  • 35,851
  • 46
  • 106
  • 159

2 Answers2

1

orderBy requires array, not object. You'd better simply convert your data. Or implement simple filter:

app.filter('keyarray', function() {
  return function(object) {
    var result = [];
    angular.forEach(object, function(value, key) {
      result.push(key);
    });
    return result;
  }
});

In html:

<div ng-repeat="key in test | keyarray | orderBy : '-toString()'">{{key}} : {{test[key]}}</div>

http://plnkr.co/edit/BHm4dv2np4ysUAlJFaO3?p=preview

Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
0

You can use -years:

<li class="year" ng-repeat="(year, data) in years | orderBy:'-years'">

Data is sorted by years in descending order.

In your question, you put "orderBy:'year':true" but should be "orderBy:'years':true"

--------EDIT---------

You should create a filter to order your object:

myApp.filter('orderObjectBy', function () {
    return function (input, attribute) {
        if (!angular.isObject(input)) return input;

        var array = [];
        for (var objectKey in input) {
            array.push(input[objectKey]);
            input[objectKey].year = objectKey;
        }

        array.sort(function (a, b) {
            a = parseInt(a[attribute]);
            b = parseInt(b[attribute]);
            return b - a;
        });
        console.log(array)
        return array;
    }
});

And then use this filter to order your repeat:

<li ng-repeat="data in years | orderObjectBy:'position'">
    {{data.year}}
    {{data.countingAgent}}
    {{data.turns}}
    {{data.cards}}
    {{data.score}}
</li>

JSFiddle: http://jsfiddle.net/ghorg12110/z4v96s4v/1/

*My answer is based on this one : AngularJS sorting by property with some changes for your situation.

Community
  • 1
  • 1
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
  • @ilyo Updated my answer – Magicprog.fr Nov 12 '15 at 15:02
  • @Magicprog.fr it keeps the order as it was. – ilyo Nov 12 '15 at 15:14
  • @ilyo Yes, sorry about that, updated once again. I've changed the order or years in fiddle, and it looks fine now :) – Magicprog.fr Nov 12 '15 at 15:23