Reputation: 5600
I have the following object and want to create a filter to group by ParentCategoryID.
[
{id : 116, Desciption : 'Item1', ParentID : 1, parent : 'Parent1'},
{id : 117, Desciption : 'Item2', ParentID : 2, parent : 'Parent2'},
{id : 118, Desciption : 'Item3', ParentID : 2, parent : 'Parent2'},
{id : 119, Desciption : 'Item4', ParentID : 1, parent : 'Parent1'}
]
so the outcome would be
Parent1
Item1
Item4
Parent2
Item2
Item3
my filter currently looks like this:
productDetailsApp.filter('groupBy', function() {
return function(list, group_by) {
var filtered = [];
var prev_item = null;
angular.forEach(list, function(item) {
if (prev_item !== null) {
if (prev_item[group_by] === item[group_by]) {
filtered.push(item);
}
}
prev_item = item;
});
console.log(filtered);
return filtered;
};
});
and html :
<div data-ng-repeat="d in details | groupBy:'ParentID'">
<h2 >{{d.parent}}</h2>
<li>{{d.Desciption}}</li>
</div>
But this outputs only outputs the last element as prev_item for first item always will be null :
Parent1
Item4
Parent2
Item3
Can someone help me please.
Upvotes: 2
Views: 1629
Reputation: 7279
Well semantically it would make a lot more sense to re-arrange your data. into something like this.
[
{
id: 1,
title: 'Parent 1',
items: [
{id: 126, description: 'Item 1'},
{....}
]
}
]
and then using nested repeats. This data structure more accurately describes the actual situation and will make your life easier. If re-arranging the data is not an option or you don't understand nested ng-repeats let me know and we can find an alternative.
Upvotes: 5