2

I'm using the built-in Angular filter OrderBy to my items by date and it works as expected in the DOM but I thought it would update the array itself so I can work with the new order of the items.

Anyone have any ideas how to achieve this?

Thanks.

P.S. I'm using AngularJS 1.3.14 if that changes anything.

2
  • ng-repeat doesn't effect the array, only what's displayed. If you want the actual array to be sorted you'd need to do so in your controller. Commented May 17, 2016 at 14:37
  • Can you show your code? Commented May 17, 2016 at 14:38

2 Answers 2

3

The filter returns a sorted copy of the array, so you could just assign it to your scope and hold a reference of the sorted array.

You would inject the $filter service in your controller and then use it programatically like this:

var orderBy = $filter('orderBy');
$scope.array = orderBy(unsortedArray, expression);

More about this filter can be found here.

Of course, if your sorting expression is dynamic, then you will have to update the reference of the array every time it changes, which is not always ideal, but is absolutely viable with smaller amounts of data.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this helped too.
2

You should re-order your array from your controller before you bind it to the DOM. This is also more performant as Angular doesn't need to recompute the order on each digest cycle.

$scope.myOrderedArray = order( $scope.myArray );

And in the DOM

<div ng-repeat="item in myOrderedArray"> ... </div>

1 Comment

Thanks help much appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.