Search code examples
angularjsangular-filtersangularjs-orderby

How to orderBy a array of objects in descending order in angularjs?


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.


Solution

  • 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