Sam Sam - 7 months ago 32
Javascript Question

AngularJs orderby filter not sorting data correctly

I have an array of customer displayed in html using ng-repeat from controller.

Here I am trying to sort the data using orderby filter. But the problem is when the array initialized it is sorted correctly in Ascending order. But when I click on Name heading it chnages the data but does not descends the data as expected. Here is a running plunker:

http://plnkr.co/4aAH08bzVUnws5RRx5RP

AngularJs:

app.controller('MainCtrl', function($scope) {

$scope.sortIt = "name";
$scope.reverse = false;

$scope.customers = [
{
name:'AAA',
city: 'Dublin',
orderTotal: 9.9563,
joined: '1947-10-10'},
{
name:'CCC',
city:'London',
orderTotal: 24.999,
joined: '2011-08-12'},
{
name:'BBB',
city:'Kenya',
orderTotal: 140.4852,
joined: '1981-06-04'},
{
name:'DDD',
city:'Tokyo',
orderTotal: 77.3654,
joined: '2006-10-30'}
]

$scope.doSort = function(propName) {
$scope.sortIt = propName;

//changing the value to opposite if true then false, if false then true
$scope.reverse = !$scope.reverse;
}


HTML:

<table class="table table-striped">
<thead>
<tr>
<th ng-click="doSort(name)" class="btn-arrange">
Name
</th>
<th>
<span>City</span>
</th>
<th>Order Total</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in customers | orderBy: sortIt: reverse">
<td>{{c.name}}</td>
<td>{{c.city}}</td>
<td>{{c.orderTotal}}</td>
<td>{{c.joined}}</td>
</tr>
</tbody>
</table>

Answer

Replace $scope.reverse = !scope.reverse; with $scope.reverse = !$scope.reverse;

You missed $ before scope.

Update:

Replace <th ng-click="doSort(name)" class="btn-arrange"> with <th ng-click="doSort('name')" class="btn-arrange">

Working Demo

Comments