Mustafa Bereket
Mustafa Bereket

Reputation: 129

Sorting an array of objects in ng-repeat using orderBy

I have an array of objects and I am trying to sort (or group) them by a boolean object attribute with using angularjs' ng-repeat functionality.

I tried using orderBy and groupBy but none of them worked.

here is my html:

<tbody md-body>
                        <tr md-row ng-repeat="item in dashboardCtrl.unAckAlertList | limitTo : 4 | orderBy: 'item.urgent'">
                            <td md-cell>
                                <i ng-if="item.urgent" class="fa fa-warning" style="font-size:22px;color:red;"></i><i ng-if="!item.urgent" class="fa fa-warning" style="font-size:22px;color:slategray;"></i><span><b> {{item.status}}</b></span>
                            </td>
                            <td md-cell>
                                {{item.MyName}} / {{item.sourceProperty}}
                            </td>
                            <td md-cell>
                                {{item.name}}
                            </td>

It never worked and I wonder why.

Upvotes: 0

Views: 3075

Answers (3)

Mustafa Bereket
Mustafa Bereket

Reputation: 129

2 things caused this error:

  1. Array should be sorted first and then you should limit the view.

  2. Whichever object attribute you wanted to sort by, you should only put the attribute name, not object itself.

instead of:

ng-repeat="item in dashboardCtrl.unAckAlertList | limitTo : 4 | orderBy: 'item.urgent'"

it should be

ng-repeat="item in dashboardCtrl.unAckAlertList | orderBy: 'urgent' | limitTo : 4 "

Upvotes: 0

Alexander Kravets
Alexander Kravets

Reputation: 4385

You should use the following syntax:

orderBy: 'urgent'

Here the quote from the documentation on using string as an orderBy parameter:

string: An Angular expression. The result of this expression is used to compare elements (for example name to sort by a property called name)...

Upvotes: 1

Brynden
Brynden

Reputation: 37653

orderBy looks for the properties you tell it to, within the current element from your array.

In the snippet you provided, you gave the current element the name of item, which is what orderBy will look for properties in.

You do not need to write orderBy: item.urgent. If you write orderBy: urgent, Angular should be able to figure the rest out.

Upvotes: 1

Related Questions