Reputation: 3112
I have a very simple array of objects and I want to sort it using $filter('orderBy')
in javascript. Somehow it doesn't seem to work. jsFiddle
Here is the code
var app = angular.module('myApp', []);
app.controller('myController', function($scope, $filter){
var person = [{
name : "Saras"
},
{
name : "Arya"
}];
$filter('orderBy')(person, 'name');
console.log(person);
});
I don't understand why I can't get this to work? Help is appreciated. And the solution should be in JS not in HTML.
Upvotes: 8
Views: 55280
Reputation: 81
$scope.person = $filter('orderBy')($scope.person , 'name', true);
true for descending order and false for ascending order
Upvotes: 0
Reputation: 21
Example:
<tr ng-repeat="friend in friends | orderBy:'-age'">
<td>{{friend.age}}</td>
<td>{{friend.name}}</td>
</tr>
Use '-' Symbol Before your expression
Upvotes: 1
Reputation: 136154
You should pass 2nd parameter as property name name
, then assign that filtered result to desire scope variable wherever you want. So there will not be any filtering needs to be done on UI ng-repeat
output.
$scope.person = $filter('orderBy')(person, 'name');
<div ng-repeat="p in person">
{{p.name}}
</div>
Forked Fiddle Here
If you wanted to see it on view you should keep that property on one of scope variable, or rather you can do this simple filtering on client side as well while displaying records.
<div ng-repeat="p in person | orderBy: 'name'">
{{p.name}}
</div>
Upvotes: 10
Reputation: 2343
Adding + or - prefix on orderBy parameter will order by + (ascending) or -(desc);
example:
<li ng-repeat="x in customers | orderBy : '-city'">
{{x.name + ", " + x.city}}
</li>
more at : http://www.w3schools.com/angular/ng_filter_orderby.asp
Or if you want to console.log it then just add name as parameter in quotations :
$filter('orderBy')(person, 'name');
Upvotes: 12