thomas
thomas

Reputation: 1174

orderBy filter works only once

Trying to sort an array of numbers either in ascending or descending order, by choice of the user.

This is my code -

Order by: 
<select ng-model="orderCriteria">
    <option value="false">ASC</option>
    <option value="true">DESC</option>
</select>

<table border="2">
<th>Number</th>

    <tr ng-repeat="num in [1, 5, 3, 6, 45, 20, 7, 2] | filter: query | orderBy:num:orderCriteria">
        <td>{{num}}</td>
    </tr>
</table>

When the page loads, numbers are automatically ordered in an ascending order. When I open the drop-down list and pick either DESC or ASC the table changes its order into a descending order (regardless of what I pick).

From that moment it doesn't matter what I have in my selection, the order is stuck on a descending order!

What am I doing wrong?

Thanks!

Upvotes: 1

Views: 770

Answers (2)

dfsq
dfsq

Reputation: 193271

To be able to change order direction easily you can simply use +/- modifiers:

<tr ng-repeat="num in numbers | orderBy: orderCriteria">
    <td>{{num}}</td>
</tr>

where orderCriteria now becomes:

<select ng-model="orderCriteria">
    <option value="+">ASC</option>
    <option value="-">DESC</option>
</select>

From orderBy documentation about predicate expressions:

An expression can be optionally prefixed with + or - to control ascending or descending sort order (for example, +name or -name). If no property is provided, (e.g. '+') then the array element itself is used to compare where sorting.

Demo: http://plnkr.co/edit/IS4jDKTtlQd6Pg9VSxVU?p=preview

Upvotes: 1

Moshe Shaham
Moshe Shaham

Reputation: 15984

The reason your code doesn't work is because the true/false values in the select box are strings which always yield 'true' in the filter expression.

You can try something like this:

<tr ng-repeat="num in [1, 5, 3, 6, 45, 20, 7, 2] | orderBy:num:(orderCriteria == 'true')">
     <td>{{num}}</td>
</tr>

Upvotes: 2

Related Questions