Tuesday, 4 November 2014

Ordering Objects in an Object for ngRepeat

I'm dipping my toes into the world of Angular and diving into the world of Firebase - I love their philosophy about everything being an object! That does mean, though, that I'm left trying to figure out how to ng-repeat a set of objects in another object (the mind boggles!), thankfully I came across this post: AngularJS Filter for Ordering Objects (Associative Arrays or Hashes) with ngRepeat by Justin Klemm and it got me working on something like this:

app.filter('orderObjectByUKDate', function() {
    return function(items, field, reverse) {
        var filtered = [];
        angular.forEach(items, function(item) {
            filtered.push(item);
        });
        filtered.sort(function (a, b) {
            return (parseInt(moment(a[field], "DD/MM/YYYY").format("X"), 10) > parseInt(moment(b[field], "DD/MM/YYYY").format("X"), 10) ? 1 : -1);
        });
        if(reverse) filtered.reverse();
        return filtered;
    };
});

It's only a little bit like this as I've got to AES decrypt the date first, but you get the idea I guess. Then it's simply a question of using it like this:

ng-repeat="thing in things | orderObjectByUKDate:'when':true"

No comments:

Post a Comment