byrdr
byrdr

Reputation: 5467

Angular combining objects into array for filter use

I have an ng-repeat loop returning a list of objects which represent calendar events. I'd like to be able to orderBy date but it looks like first I need to push the returned objects into a single array.

Here is my angular view:

<div class="calendar">

<p>{{cal}}</p>
<div ng-repeat="items in cal">

        <a href="/events/{{items.day}}">
          <article class="eventslist">
           <div class="numberedDate">
               <h3>{{items.day}}</h3>
            </div>
            <div class="calInfo">
            <h5>{{items.title}}</h5>
               <p>{{items}}&nbsp;<a>more</a></p>
            </div>
           </article>


      </div><!-- ng-repeat items -->
</div><!-- calendar -->

items is currently returning:

{"day":"21","title":"ok","summary":"ok","description":"ok","_id":"53ee9f0fc6aed109c6d33cfd"}
{"day":"2","title":"ok","summary":"ok","description":"ok","_id":"53ee9f038782309c6d892"}
{"day":"27","title":"ok","summary":"ok","description":"ok","_id":"533240fc6ae32433chd"}

Is there a way to wrap these returned objects into an array [] so that they could have an orderBy 'day' called on them?

Upvotes: 0

Views: 110

Answers (1)

Caspar Harmer
Caspar Harmer

Reputation: 8117

If you just need to get the items into an array, the below loop will do it:

var arr = [];
angular.forEach(items, function (item) {
    arr.push(item);
});

I know your data has a complicated structure, so you may need a couple of loops to pull out the objects you need and flatten the array.

Once your data is structured, Then the code below will work. It will handle an array or an object as long as you get the ng-repeat parameters right. (I've tested it on array):

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

Note the parseInt call in the sort function. I have actually seen a function passed in as a parameter inside the ng-repeat but you can investigate that later if you like.

Anyway, Here is a working demo jsFiddle

Upvotes: 1

Related Questions