NoobSter NoobSter - 9 days ago 5
AngularJS Question

Angular sort toggle not working correctly

$scope.searchObject = {
from: 0,
hydrate: false,
size: 12,
sort: 'timestamp:desc'
};

$scope.sort = function(a) {
var ascend = a + ':' + 'asc';
var descend = a + ':' + 'desc';
if ($scope.searchObject.sort === ascend) {
$scope.searchObject.sort = descend;
}
if ($scope.searchObject.sort === descend) {
console.log('is desc')
$scope.searchObject.sort = ascend;
console.log('sort : ', $scope.searchObject.sort)
} else {
$scope.searchObject.sort = descend;
}
};


<div class="sort-info">
<label>Sort:</label>
<a class="sort-item" ng-click="sort('timestamp')"> Date
<div class="sort-arrow" >
<i ng-show="searchObject.sort === 'timestamp:asc'" class="fa fa-caret-down"></i>
<i ng-show="searchObject.sort === 'timestamp:desc'" class="fa fa-caret-up"></i>
</div>
</a>
<a class="sort-item" ng-click="sort('followers')">Followers
<div class="sort-arrow">
<i ng-show="searchObject.sort === 'followers:asc'" class="fa fa-caret-down"></i>
<i ng-show="searchObject.sort === 'followers:desc'" class="fa fa-caret-up"></i>
</div>
</a>
</div>




Once it the sort hits desc again, it will not switch back to asc. The conditional is being triggered, and it console.logs the appropriate sort within search object, but the view isn't changed.

Answer

Need an if else

$scope.sort = function (a) {
    var ascend = a + ':' + 'asc';
    var descend = a + ':' + 'desc';
    if ($scope.searchObject.sort === ascend) {
      $scope.searchObject.sort = descend;
    }else if ($scope.searchObject.sort === descend){
      console.log('is desc')
      $scope.searchObject.sort = ascend;
      console.log('sort : ', $scope.searchObject.sort)
    }
    else {
      $scope.searchObject.sort = descend;
    }
  };
Comments