Saras Arya Saras Arya - 1 year ago 72
AngularJS Question

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

I have a very simple array of objects and I want to sort it using

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');

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.

Answer Source

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">

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'">

Demo here