Param Singh
Param Singh

Reputation: 1366

AngularJS Custom Filter orderBy sortPredicate not working

The problem is that I have an array of recipe objects. Each recipe object has some comments on it. I want to sort the array in angularJS controller using the $filter service provided by angular.

 $scope.recipes = $filter('orderBy')($scope.data, function(recipe) {
    return recipe.comments.length;
  });

But its not giving the required results. However, I'm able to achieve the desired results using the JS array sort functionality like this

$scope.data.sort(function(a, b) {
     if (a.comments.length < b.comments.length) return 1;
     if (b.comments.length < a.comments.length) return -1;
     return 0;
    });

The Plunkr for the same scenario is : http://plnkr.co/edit/L9Bt67xHRCJLBoWG8EZp?p=preview

Thanks in advance. Please Help!

Upvotes: 2

Views: 5888

Answers (3)

Oliver Salzburg
Oliver Salzburg

Reputation: 22099

$scope.recipes = $filter('orderBy')($scope.data, "comments.length", true)

The filter expects an expression, not a function.

Upvotes: 0

Ed Knowles
Ed Knowles

Reputation: 1925

Added this as another answer, since you want to manage it in your controller and you want the reverse, add true as the final arg in $filter

Documentation $filter('orderBy')(array, expression, reverse)

Example

$scope.recipes = $filter('orderBy')($scope.data, function(recipe) {
  return recipe.comments.length;
}, true);

I'm pretty sure you can also set the reverse to a var in scope if you wish.

Upvotes: 0

Ed Knowles
Ed Knowles

Reputation: 1925

It can be done a lot simpler using orderBy

http://plnkr.co/edit/B0fMi7FotgmG2tkCjySt?p=preview

 <ul>
   <li ng-repeat="r in recipes | orderBy:'-comments.length'">
     {{r.title}} - {{r.comments.length}}
   </li>
 </ul>

Upvotes: 2

Related Questions