角度排序切换无法正常工作

时间:2016-11-23 21:00:07

标签: javascript angularjs

$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>

一旦排序再次击中desc,它就不会切换回asc。正在触发条件,并且它会在搜索对象中对console.log采用适当的排序,但视图不会更改。

1 个答案:

答案 0 :(得分:3)

需要else if

$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;
    }
  };