Skip to content

Instantly share code, notes, and snippets.

@justinklemm
Last active December 23, 2015 10:49
Show Gist options
  • Save justinklemm/6624575 to your computer and use it in GitHub Desktop.
Save justinklemm/6624575 to your computer and use it in GitHub Desktop.
AngularJS Filter for Ordering Objects (Associative Arrays or Hashes) with ngRepeat
<ul>
<li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }}</li>
</ul>
var app = angular.module('sample');
// inside your controller
$scope.items = {};
$scope.items['color-1'] = {color: "red"};
$scope.items['color-2'] = {color: "green"};
$scope.items['color-3'] = {color: "blue"};
// define filter on app
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
if(a[field] > b[field]) return 1;
if(a[field] < b[field]) return -1;
return 0;
});
if(reverse) filtered.reverse();
return filtered;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment