Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting values of a hash object in ngRepeat - angularJS

I have an object like this:

$scope.phones = new Object();
$scope.phones['id1'] = {
    "name":"Phone Name1",
    "dateReleased":"2012-1-09 15:48:24"
};
$scope.phones['id2'] = {
    "name": "Phone Name2",
    "dateReleased":"2012-3-12 15:32:11"
};
$scope.phones['id3'] = {
    "name": "Phone Name3",
    "dateReleased":"2012-2-10 13:53:32"
};

I'm displaying this using ngRepeat. I'm not able to order by dateReleased. Also, ordering in reverse isn't working. My ngRepeat looks this:

<li ng-repeat="phone in phones | orderBy:dateReleased:true">
    <p>{{phone.name}}</p>
    <p>{{phone.dateReleased}}</p>
</li>
like image 1000
Chai Nadig Avatar asked Nov 25 '12 15:11

Chai Nadig


1 Answers

While ngRepeat can iterate a hash object, like $scope.phones in your example, the built-in orderBy filter will not work. I believe this is due to the way objects are stored. As other's have noted, you need to convert the hash to an array. While you can do this using the methods suggested above, I prefer to do it using a custom filter. This gives me the benefit of not having to alter my hash directly, and also let's me reuse the filter with other hashes.

yourApp.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
});

This filter converts the object into a standard array and sorts it by the field you specify. You can use the orderObjectBy filter exactly like orderBy, including a boolean value after the field name to specify whether the order should be reversed. In other words, false is ascending, true is descending.

<li ng-repeat="phone in phones | orderObjectBy:'dateReleased':true">
  <p>{{phone.name}}</p>
  <p>{{phone.dateReleased}}</p>
</li>

I've got a post on my blog regarding this topic.

like image 97
Justin Klemm Avatar answered Oct 19 '22 22:10

Justin Klemm