Reputation: 2053
We have an ng-repeat as given below
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:(isSortRequired?'-name':'')">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
which has to be sorted based on name
only if the flag isSortRequired
is true
.otherwise no sorting is required. This works fine if the no. of records is less than or equal to 10 .if the number of records is greater than 10 and the flag is false
the table shows the records in scrambled order.We want it to be displayed in the order as same as in the object.
Why is this behaviour? Here is a plunker to illustrate the issue.
Upvotes: 1
Views: 526
Reputation: 38663
You can solve it by use reverse
option in your order by
I have changed your code
<table class="friend">
<tr>
<th>
**<a href="" ng-click="predicate = 'name'; reverse=!reverse">Name</a>**</th>// changes here
<th>Phone Number</th>
<th>Age</th>
</tr>
**<tr ng-repeat="friend in friends | orderBy:predicate:reverse">**// changes here
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
I have added a scope object in your controller for name sorting
$scope.predicate = '-name';
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.isSortRequired = true;
$scope.friends =
[{name:'john', phone:'555-1212', age:10},
{name:'mary', phone:'555-9876', age:19},
{name:'mike', phone:'555-4321', age:21},
{name:'julie', phone:'555-8765', age:29},{name:'A', phone:'555-1212', age:10},
{name:'B', phone:'555-9876', age:19},
{name:'C', phone:'555-4321', age:21},
{name:'D', phone:'555-5678', age:35},
{name:'E', phone:'555-8765', age:29},{name:'F', phone:'555-1212', age:10},
{name:'G', phone:'555-9876', age:19},
{name:'H', phone:'555-4321', age:21},
{name:'I', phone:'555-5678', age:35},
{name:'J', phone:'555-8765', age:29}];
}]);
$scope.predicate = '-name';// ans also some change here
</script>
I have updated your plunker Demo
The plunker only help to sort the name column only, if you want to sort all columns, then you need to do the same way for your all columns.
Upvotes: 0
Reputation: 3644
From the angular documentation for the orderBy filter
If no property is provided, then the array element itself is used to compare where sorting.
The scrambled effect is caused by angular adding a $$hashKey
property to each object in your array. The $$hasKey
is not guaranteed to be the same order of the initial array thus making them appear to be 'randomized'.
So either you order the array before-hand or use a custom filter that applies the orderBy filter only if you need to ordering.
A custom filter could look something like this
.filter('filter', ['$filter', function($filter)
{
var orderBy = $filter('orderBy');
return function(input, property, use)
{
return use ? oderBy(input, property) : input;
};
}
Upvotes: 2