Ordering and filtering objects with ng-repeat

adamkdean

Adam K Dean

Posted on March 26, 2014

Ordering and filtering objects with ng-repeat

AngularJS allows you to iterate over collections using the ng-repeat directive. You have the ability to order and filter the collection, but this only works for arrays, not for objects. You'd think that you'd retain the functionality of arrays, considering the object is treated like one, but you don't.

The solution to this is to push the contents of the object into an array using a filter. By keeping the references intact, we are still able to bind to the objects, as they are essentially the same object.

.filter('objectAsArray', function() {
    return function(object) {
        var array = [];
        for (item in object) {
            array.push(object[item]);
        }
        return array;
    }
});
Enter fullscreen mode Exit fullscreen mode

Let's look at what we'd need if we wanted to order and/or filter an array:

<p ng-repeat="item in itemArray | orderBy: 'order' | filter: {visible: true}">
  {{item}}
</p>
Enter fullscreen mode Exit fullscreen mode

But what if that was an object? Well, we just pop the objectAsArray filter in:

<p ng-repeat="item in itemObj | objectAsArray | orderBy: 'order' | filter: {visible: true}">
    {{item}}
</p>
Enter fullscreen mode Exit fullscreen mode

This is indeed a very useful little filter.

View the live plunkr example here.

💖 💪 🙅 🚩
adamkdean
Adam K Dean

Posted on March 26, 2014

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related