排序表排序&动态列

时间:2016-12-21 19:29:54

标签: angularjs sorting filter html-table ng-repeat

我正在尝试排名表:

我有一个对象scores,其中包含总分数,每个"挑战"与此挑战相关的要点。我的主要问题是通过scores为每个挑战创建一个th标记&以后对它们进行排序。

目标:

  • 挑战的数量必须是动态的
  • 按总计(已完成)排序&通过挑战

我的问题:

  • 如何使用ng-repeat进行挑战阵列
  • 如何排序这些

我的进步:



var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.sortType = 'points';
    $scope.sortReverse = false;
		$scope.scores = { 
      "6":{
        "total":5, 
        "challenges":{
          "1":{
        "challengeId":1},
      "2":{
        "point":2,
        "challengeId":2}
      }
    },
    "21":{
    "total":2, 
    "challenges":{
      "1":{
        "point":1,
        "challengeId":1},
      "2":{
        "point":1,
        "challengeId":2}
          }
        },
      }
}

myApp.filter('orderObjectBy', function() {
    return function(items, field, reverse) {
      var filtered = [];
      angular.forEach(items, function(item) {
        filtered.push(item);
      });
      filtered.sort(function (a, b) {
        return (a[field] > b[field] ? 1 : -1);
      });
      if(reverse) filtered.reverse();
      return filtered;
    };
  });

<div ng-controller="MyCtrl">
  <table>
      <tr>
        <th>Rank</th>
        <th>
          <span ng-click="toggleSort($index);sortReverse=false">+</span> 
          Total 
          <span ng-click="toggleSort($index);sortReverse=true">-</span>
        </th>
        <th ng-repeat="challenge in scores.challenges">
          <span ng-click="toggleSort($index);sortReverse=false">X</span> 
          Challenge n° 
          <span ng-click="toggleSort($index);sortReverse=true">Y</span>
        </th>
      </tr>
      <tbody ng-repeat="score in scores | orderObjectBy:sortType:sortReverse">
        <tr>
          <td>{{ $index+1 }}</td>
          <td>{{ score.total }}</td>
          <td ng-repeat="challenge in score.challenges">{{ challenge.point }}</td>
        </tr>
      </tbody>
    </table>
</div>
&#13;
&#13;
&#13;

  

JSFiddle


谢谢!

1 个答案:

答案 0 :(得分:0)

我更新了小提琴。当您想通过嵌套值进行排序时,这是您指定orderString的方式(在您的情况下,它将由特定的质询ID):

$scope.orderType = "challenges."+challengeId+'.point';

我还添加了一个过滤器,用于转换数组中的对象:

.filter('orderObjectBy', function() {
  return function (items, field, reverse) {
    var filtered = [];

    angular.forEach(items, function(item, key) {
      item.key = key;
      filtered.push(item);
    });

    return filtered;
  };
});

然后你的HTML应该是这样的:

<tbody ng-repeat="score in scores| orderObjectBy | orderBy: orderType:sortReverse">
    <tr>
     <td>{{ $index+1 }}</td>
     <td>{{ score.total }}</td>
     <td ng-repeat="challenge in score.challenges">{{ challenge.point }}</td>
    </tr>
</tbody>

检查此工作样本:http://jsfiddle.net/Lvc0u55v/13564/