我目前有一个模板:
<div class="choice-pair" ng-repeat="choicePair in pastChoices track by $index" ng-init="p1Result = getP1Result(choicePair); choiceNum = $index + 1;">
<div class="turn-count cell"><strong>{{choiceNum}}</strong></div>
<div class="p1 cell" ng-class="{win: p1Result === 1, lose: p1Result === -1, draw: p1Result === 0}"><strong>{{choicePair[0]}}</strong></div>
<div class="p2 cell" ng-class="{win: p1Result === -1, lose: p1Result === 1, draw: p1Result === 0}"><strong>{{choicePair[1]}}</strong></div>
</div>
pastChoices是一个包含长度为2的子数组的数组,例如:
[['A', 'B'],['B', 'C'],['A', 'A'],['C', 'A']]
但是由于需要更改服务器上的数据存储类型,我不得不压扁这个结构,以便现在内联pastChoices:
['A', 'B', 'B', 'C', 'A', 'A', 'C', 'A']
我是否可以对模板进行一些小改动,让它通过递增2来迭代新的pastChoices格式,然后我可以选择如下的选择对:
<div class="choice-pair" ng-repeat="choices in pastChoices track by $index" ng-init="p1Result = getP1Result(pastChoices[$index], pastChoices[$index + 1]);">
<div class="turn-count cell"><strong>{{$index + 1}}</strong></div>
<div class="p1 cell" ng-class="{win: p1Result === 1, lose: p1Result === -1, draw: p1Result === 0}"><strong>{{pastChoices[$index]}}</strong></div>
<div class="p2 cell" ng-class="{win: p1Result === -1, lose: p1Result === 1, draw: p1Result === 0}"><strong>{{pastChoices[$index + 1]}}</strong></div>
</div>
这看起来它会得到我想要的数据,除了它将遍历pastChoices数组的每个元素,在那里我希望它有效地跳过奇数元素。
答案 0 :(得分:1)
由于您没有使用choices
,因此您可以将结果数量限制为ng-repeat中总数的一半:
<div class="choice-pair" ng-repeat="choices in (pastChoices | limitTo: pastChoices.length / 2 ) track by $index ">
<div class="turn-count cell"><strong>{{($index * 2) + 1}}</strong></div>
<div class="p1 cell" ng-class="{win: p1Result === 1, lose: p1Result === -1, draw: p1Result === 0}"><strong>{{pastChoices[($index * 2)]}}</strong></div>
<div class="p2 cell" ng-class="{win: p1Result === -1, lose: p1Result === 1, draw: p1Result === 0}"><strong>{{pastChoices[($index * 2) + 1]}}</strong></div>
</div>
https://docs.angularjs.org/api/ng/filter/limitTo
如果您的数组不是偶数长度,这显然会失败。