Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-repeat groupBy and Keep order

Im using this filter https://github.com/a8m/angular-filter#groupby to order my data like so, and it works great:

<div ng-repeat="(key, value) in tags.tags.objects | groupBy:'category.name' ">

Now Im trying to keep the order of that groups, by category.order.

Is this possible?

I tried piping it like so:

<div ng-repeat="(key, value) in tags.tags.objects | groupBy:'category.name' | orderBy:'category.order' ">

But it does not make any difference

like image 701
Harry Avatar asked Sep 18 '14 20:09

Harry


3 Answers

orderBy filter does not work with objects in ngRepeat. So, what you can do is something like this:

<!-- 
     Note: toArray filter also attaches a new property $key
     to the value containing the original key that was used in the object. 
-->

<div ng-repeat="tags in tagsList | groupBy:'prop' | toArray:true | orderBy:'$key'">
  Group name: {{ tags.$key }}
  <p ng-repeat="tag in tags | orderBy:'prop'">
     {{ tag.name }}
  </p>
</div>

See: toArray filter

like image 138
a8m Avatar answered Nov 11 '22 13:11

a8m


groupBy should always be the last one in the ng-repeat.. so set orderBy first and groupBy last and then you can use track by $index so the normal ng-repeat will be.

ng-repeat="item in items orderBy:'price' | groupBy:'name' track by $index"

... Hope it helps even its little late!

like image 34
Sijan Gurung Avatar answered Nov 11 '22 13:11

Sijan Gurung


To partially of djsiz's answer (track by isn't necessary and it was missing a pipe), you could do this:

<div ng-repeat="(key, value) in tags.tags.objects | orderBy:'category.order' | groupBy:'category.name'">

The groupBy creates an object but the orderBy needs an array... if you orderBy before you group, it should sort properly

https://jsfiddle.net/r0m4n/kfho6r26/

like image 3
r0m4n Avatar answered Nov 11 '22 12:11

r0m4n