ng-repeat:识别排序列表中元素值的更改

时间:2016-12-28 04:53:16

标签: javascript angularjs

我正在使用ng-repeat创建一个表。此表有一个名为Season的列,显然由{{episode.season}}填充。源数据按季节排序。

我想在每个季节的最后<tr>添加一个班级,即当季节发生变化时,例如

--------------------------
EPISODE 1 | SEASON 1
--------------------------
EPISODE 2 | SEASON 1
--------------------------
EPISODE 3 | SEASON 1       <- THIS ROW SHOULD HAVE DIFFERENT FORMATTING
--------------------------
EPISODE 1 | SEASON 2 
--------------------------

使用vanilla JavaScript,我会遍历表格,同时将每个季节<td>与下一季比较,如果存在差异则添加一个类。

但是,我不知道如何使用angularjs来做到这一点。任何帮助表示赞赏。

我决定通过在服务器端循环数据集,为此设置适当的布尔值,然后在UI上使用ng-class来确定每个季节的最后一集。它似乎比循环渲染的HTML表格更简洁,更整洁。

3 个答案:

答案 0 :(得分:3)

您可以使用$last ng-repeatng-class来设置每个季节的最后一集

数据

$scope.shows = [{
        "season" : "season 1",
        "episodes" :["episode 1","episode 2","episode 3"]
    },
    {
      "season" : "season 2",
      "episodes" : ["episode 1","episode 2","episode 3"]
    },
    {
      "season" : "season 3",
      "episodes" : ["episode 1","episode 2","episode 3"]
    }
    ];

<tbody ng-repeat="show in shows">
     <tr ng-class="$last ? 'endSeason' : ''" ng-repeat="episode in show.episodes">
      <td>{{show.season}}</td>
      <td>{{episode}}</td>
    </tr> 
    </tbody>

<强> FULL EXAMPLE

答案 1 :(得分:0)

假设绑定到控制器语法。

<div ng-repeat="episode in $ctrl.episodes" ng-class="'final-of-type': $ctrl.isDifferent($index);'"></div>

然后在你的指令中:

this.episodes = data; // not sure how you're getting this
this.isDifferent = function(i) {
     return (i === episodes.length - 1) || (episodes[i].season !== episodes[i + 1].season)
}

应该这样做或者你。

答案 2 :(得分:0)

您可以使用groupBy按季节对所有系列进行分组,然后迭代每个季节,并使用所需的类标记$last系列(最终类型) :

&#13;
&#13;
(function(angular) {
  'use strict';
var myApp = angular.module('app', ['angular.filter']);

myApp.controller('MyController', ['$scope', function($scope) {
    $scope.episodes = [
    {season:'1',episode:'2'},
    {season:'2',episode:'1'},
    {season:'1',episode:'1'},
    {season:'1',episode:'3'},
    {season:'2',episode:'2'},
    {season:'0',episode:'1'}
    ]
}]);
})(window.angular);
&#13;
.final-of-type {
background-color:grey;
}
td, th {
border: 1px solid #dddddd;
}
&#13;
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>

  <body ng-app="app">
    <div ng-controller="MyController">
      <table>
        <thead>
          <tr>
            <th>Season</th>
            <th>Episode</th>
          </tr>
        </thead>
        <tbody ng-repeat="(key, value) in ::episodes | groupBy: 'season' | orderBy: 'key'">
          <tr ng-repeat="episode in ::value | orderBy: 'episode'" ng-class="{'final-of-type': $last}">
            <td>{{::episode.season}}</td>
            <td>{{::episode.episode}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </body>
&#13;
&#13;
&#13;