Search code examples
javascriptarraysangularjssortingangularjs-orderby

Angularjs - simple ng-repeat orderBy filter wont work


I have a simple array of objects:

  $scope.asd = [{"approved":true,"id":"542fb8972be5b5cc4356dd51","username":"k"},
{"approved":false,"id":"542fbea3bae6fe4449c838d5","username":"tototod"},
{"approved":false,"id":"54324929afafdb92209b2474","username":"asdasd"}
];

then in view i want to print the values and orderBy id or username like this:

<div ng-repeat="row in asd | orderBy:username:reverse">
{{row.username}}
</div>

OR

<div ng-repeat="row in asd | orderBy:id:reverse">
    {{row.id}}
    </div>

but it doesnt works, what it can be?

I have no console errors and i just followed the guide here: https://docs.angularjs.org/api/ng/filter/orderBy

any help appriciated, thanks


Solution

  • In your examples username and id should be quoted! That expression has to evaluate to a string which will be used to look up the object property. Please refer to the documentation again, and you will see that predicate is a variable which resolves to a string value.

    Solution:

    <div ng-repeat="row in asd | orderBy:'username':true">
        {{row.username}}
    </div>
    

    Also, reverse should evaluate to a boolean expression.

    Working fiddle for your data.