我正在寻找一种方法来呈现一个ios一致但不会在所有重复实例上运行的运行索引。
<div class="cell" ng-repeat="c in arr">
<div ng-if="c !== false">{{ <someIndex> }}</div>
</div>
假设arr = ['word-y', false, false, 'word-x', 'word-z', false, ...]
,某些单元格将显示内部值,而某些单元格则不会。
我有兴趣显示一个运行计数,以便第一个单元格显示1
,第二个和第三个单元格自然为空,第四个将显示2
,等等(这就是$index
对我没用的原因)。
注意:
答案 0 :(得分:1)
在您的范围内保留另一个数组,如果条目不为假,则其值为数字
$scope.runningCount = [ 1, -1,-1,3,4,...]
现在在你的html中使用ng-repeat索引来显示正确的文本/计数
<div class="cell" ng-repeat="c in arr">
<div ng-if="c !== false">{{ runningCount[{{index}} }}</div>
</div>
答案 1 :(得分:1)
<强>更新强>
问题是你正在失去戒备。你可以用一个数组做到这一点。你需要一组对象。
这里有一个很好的解释这个问题: Binding inputs to an array of primitives using ngRepeat => uneditable inputs
然后您可以尝试我向您提出的任何其他解决方案,例如:
$scope.arr = [{value: 'word-y'}, {value:'sd'}, {value:false}, {value:'word-x'}, {value:'word-z'}];
和
<style type="text/css">
.list-cell {
counter-reset: cell;
}
.cell_iter:before {
counter-increment: cell;
content: "position " counter(cell) ". ";
}
</style>
[..]
<ul class="list-cell">
<li ng-repeat="c in arr track by $index">
<span ng-class="{'cell_iter': c.value !== false}">{{ c.value }}</span>
</li>
</ul>
此处的示例:https://plnkr.co/edit/z0d27M8otjc16THMUPkA
OLD回复 可行的解决方案:
(解决方案1)在控制器中修改数组以获得索引值:
var newArr = arr.filter(function(value){return value!== false})
(解决方案2)或在您的模板中:
<div class="cell" ng-repeat="c in arr | filter:filterFn">
在你的控制器中:
$scope.filterFn = function(c){ return c !== false}
(解决方案3)我最喜欢的解决方案,只有css:
<div class="list-cell">
<div class="cell" ng-repeat="c in arr">
<div class="cell_iter" ng-if="c !== false">{{ <someIndex> }}</div>
</div>
</div>
CSS:
.list-cell {
counter-reset: cell;
}
.cell_iter:before {
counter-increment: cell;
content: "position " counter(cell) ". ";
}
(其他解决方案)您可以在ng-repeat中使用ng-init。创建一个新变量......但这个解决方案将是丑陋的。
更新添加NG-INIT:
这个想法是在父上下文中创建一个新属性来重复ng-ng并在ng-repeat中重复另一个不同的上下文。
我们将在模板(丑陋)中完成所有这些:
<ul class="example-animate-container" ng-init="$counterHelper=0">
<li class="animate-repeat" ng-repeat="c in arr track by $index" ng-init="$parent.$counterHelper = c !== false?$counterHelper +1:$counterHelper; p={}; p.value=c; p.$counter = $counterHelper;">
[{{$index + 1}}] [{{ p.$counter }}] {{ p.value }}
</li>
</ul>
这里有一个例子:https://plnkr.co/edit/z0d27M8otjc16THMUPkA?p=preview
答案 2 :(得分:0)
我相信只需使用angular filter来过滤掉#34;就会有一个简单而优雅的解决方案。例如,数组中的falsey元素试试这个:
<div class="cell" ng-repeat="c in $ctrl.arr | filter: '!false' track by $index">
<div>{{ c }} {{ $index }}</div>
</div>
(请注意,您实际上不再需要ng-if
了!)
干杯!