在Angular中为orderBy设置ng-show的初始状态

时间:2015-01-22 05:02:02

标签: angularjs angularjs-ng-click angularjs-orderby

尝试设置我为可排序列表显示的箭头的初始状态。有三列,每一列都有绑定到ng-click的链接,点击后会对列表进行排序。

它正在我需要的时候工作,但是在点击之前,向上和向下箭头的状态不会显示。当我点击一个时,另一个消失了。我希望所有箭头在用户点击之前始终显示,并且每个箭头在点击三者中的任意一个时改变方向。

基本链接是:

<a href="javascript:void(0)" ng-click="orderByField='dateAdded'; reverseSort = !reverseSort" class="ghostButtonSort dateLabel flrt">Date Received
    <span ng-show="orderByField == 'dateAdded'">
        <span ng-show="!reverseSort">^</span>
        <span ng-show="reverseSort">v</span>
    </span>
</a>

现在我只是在范围内进行了基本设置:

$scope.orderByField = 'conditionId';

3 个答案:

答案 0 :(得分:2)

使用控制器中的默认值初始化值:

$scope.orderByField = 'dateAdded';
$scope.reverseSort = false;

这是一个简单的小提琴,演示了工作排序行为:http://jsfiddle.net/kxotrmj6/2/

在此演示中,您可以通过单击列标题更改排序列,并通过单击活动排序列旁边显示的插入符来更改排序方向。这是通过以下方式实现的:

<强> HTML

<table id='peopleTable'>
  <thead>
      <th>
          <a href="#" ng-click="sortOn = 'firstName'">First Name</a> 
          <i class="fa"
             ng-click="sortReverse = !sortReverse"
             ng-show="sortOn == 'firstName'"
             ng-class="sortReverse ? 'fa-caret-down' : 'fa-caret-up'">
             </i>
      </th>
      <!-- snip -->
  </thead>
  <tbody>
      <tr ng-repeat='person in people | orderBy:sortOn:sortReverse'>
          <td>{{person.firstName}}</td>
          <td>{{person.lastName}}</td>
          <td>{{person.favoriteColor}}</td>
      </tr>
  </tbody>
</table>

<强>控制器

function MyCtrl($scope) {
    $scope.sortOn = 'lastName';
    $scope.sortReverse = false;

    $scope.people = [
        {
            firstName: 'Joe',
            lastName: 'Smith',
            favoriteColor: 'Orange'
        }, {
            firstName: 'Jane',
            lastName: 'Doe',
            favoriteColor: 'Gray'
        }, {
            firstName: 'Zoey',
            lastName: 'Tester',
            favoriteColor: 'Blue'
        }];
}

我使用FontAwesome作为插入符号,但您可以使用文字或图片。 sortReversesortOn都在控制器中初始化,因此它们具有默认值,并且将始终反映在UI中。

答案 1 :(得分:0)

使用ng-init添加默认值,如下所示

<a href="javascript:void(0)" ng-click="orderByField='dateAdded'; reverseSort = !reverseSort" class="ghostButtonSort dateLabel flrt">Date Received
 <span ng-show="orderByField == 'dateAdded'"><span ng-show="!reverseSort" ng-init="reverseSort = true">^</span>
 <span ng-show="reverseSort">v</span></span></a>

答案 2 :(得分:-1)

<td>
    <a href="#" ng-click="sortType = 'firstName'; sortReverse = !sortReverse">
        firstName :
        <span ng-show="sortType == 'firstName' && !sortReverse" class="fa fa-caret-down"></span>
        <span ng-show="sortType == 'firstName' && sortReverse" class="fa fa-caret-up"></span>
    </a>
</td>