NG重建第二次运行索引,与$索引分开



我正在寻找一种呈现运行索引的方法

<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对我没有用)。

注意:

  1. 计算值的数组必须在第一次计算后能够更改,并且值将重新计算。
  2. 我目前在此项目中不使用jQuery,如果可能的话,我想保持这种方式。

如果条目不是false

$scope.runningCount = [ 1, -1,-1,3,4,...]

现在在您的HTML内部使用ng-repeat索引显示正确的文本/count

<div class="cell" ng-repeat="c in arr">
    <div ng-if="c !== false">{{   runningCount[{{index}}   }}</div>
</div>

update

问题是您正在失去重新态度。您可以使用一个数组来完成。您需要一系列对象。

您对此问题有很好的解释:使用ngrepeat =&gt绑定输入到一系列原始词;不可编辑的输入

然后,您可以尝试我建议的任何其他解决方案,例如:

$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

旧回复提出解决方案:

(解决方案1)在您的控制器中修改数组以具有索引值:

var newArr = arr.filter(function(value){return value!== false})

(解决方案2)或模板中:

<div class="cell" ng-repeat="c in arr | filter:filterFn">

和yout Controller中:

 $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重复中使用NG-Init。创建一个新的变量...但是此解决方案将很难看。

更新添加ng-init:

这个想法是在父上下文中创建一个新属性,以进行NG重复,并在NG重复中创建另一个不同的上下文。

我们将在模板(丑)中完成所有这些:

  <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

我相信,只需使用一个角滤波器来"滤除"数组中的假元素,就可以使用一个简单而优雅的解决方案。

<div class="cell" ng-repeat="c in $ctrl.arr | filter: '!false' track by $index">
    <div>{{ c }} {{ $index }}</div>
</div>

(注意您实际上不再需要ng-if!)

欢呼!

最新更新