使用具有优先级的角度对列进行排序

时间:2014-09-08 16:29:52

标签: javascript html angularjs angularjs-orderby

我正在尝试使用angular来对列进行排序。我已经得到了angular tutorial的代码。

现在我无法让一行始终保持在最高位置。例如,我将有一个名为mainContact的列。此值只能为一个人设置为true。我希望mainContact为true的人始终保持在表的顶行,而其他人则随着排序而变化。老实说,对于如何做到这一点的想法,我有点失落。

我把它放在一起来展示我到目前为止所拥有的东西:http://jsfiddle.net/Beastwood/m44fy1j5/

<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
 <table class="friend">
<tr>
  <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a></th>
  <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
    <th>MAIN CONTACT</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  <td>{{friend.name}}</td>
  <td>{{friend.phone}}</td>
  <td>{{friend.age}}</td>
     <td>{{friend.mainContact}}</td>
</tr>
</table>
</div>

JS FIle

var myApp = angular.module('myApp', [])
.controller('ExampleController', ['$scope', function($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:10, mainContact:true},
       {name:'Mary', phone:'555-9876', age:19, mainContact:false},
       {name:'Mike', phone:'555-4321', age:21, mainContact:false},
       {name:'Adam', phone:'555-5678', age:35, mainContact:false},
       {name:'Julie', phone:'555-8765', age:29, mainContact:false}];
   $scope.predicate = '-age';
   }]);

1 个答案:

答案 0 :(得分:2)

您可以将一组属性名称传递给过滤器,并使用-为属性名称添加前缀以反转...

<tr ng-repeat="friend in friends | orderBy:['-mainContact', (reverse ? '-' : '') + predicate]">
    ...
</tr>
  • -mainContact - 首先按mainContact属性按相反顺序排序 (因为true = 1,false = 0)
  • (reverse ? '-' : '') + predicate - 然后按谓词排序,如果反向为真,则追加-

Live Demo