8

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.

4 Answers 4

12

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');
Sign up to request clarification or add additional context in comments.

1 Comment

U can also use ! : <li ng-repeat="x in customers | orderBy : '!city'">
10

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>

Demo here

9 Comments

It doesn't work... Could you post the link of a working fiddle... From the one given in question.
I have updated my answer, could you please look into the fiddle which I have in my answer?
Can't the $scope.person array be modified in the controller file?
@SarasArya yes, it can be modified from controller
if you want to sort in descending order then set true in third parameter like this: $scope.person = $filter('orderBy')(person, 'name', true);
|
1

Example:

<tr ng-repeat="friend in friends | orderBy:'-age'">
    <td>{{friend.age}}</td>
    <td>{{friend.name}}</td>
</tr>

Use '-' Symbol Before your expression

2 Comments

Hi Muhammad, can you explain what your answer provides in addition to the already given answers?
@ArtjomB. I give that what expression should have to use beside value . for clarification . i give comments
0

$scope.person = $filter('orderBy')($scope.person , 'name', true);

true for descending order and false for ascending order

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.