ng-repeat循环计数内的角度ng重复

时间:2016-07-07 14:51:48

标签: javascript angularjs

我有以下代码:

<div ng-repeat="list in [[1,2,3,4], [1,2,3,4]] track by $index">
    <div id="{{counter}}" ng-repeat="listChild in list track by $index">
        {{listChild}}
    </div>
</div>

我想让counter成为元素的编号,但是相对于整个父数组。我怎样才能使它工作,所以div不断计算,而不是两个单独的数组。是这样的:

<div>
    <div id="1">
        {{listChild}}
    </div>
    <div id="2">
        {{listChild}}
    </div>
    <div id="3">
        {{listChild}}
    </div>
    <div id="4">
        {{listChild}}
    </div>
</div>
<div>
    <div id="5">
        {{listChild}}
    </div>
    <div id="6">
        {{listChild}}
    </div>
    <div id="7">
        {{listChild}}
    </div>
    <div id="8">
        {{listChild}}
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

下面的代码说明了父数组中不同的数组长度。 $scope.precedingCount跟踪滚动总数直到给定内部数组的开头

&#13;
&#13;
var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.counter = 0;

  $scope.data = [[1,2,3,4], ['a','b','c','d', 'e', 'f'], ['any', 'other', 'data', 'needed']];

  $scope.precedingCount = {
    0: 0
  };

  for(var i=1; i<$scope.data.length; i++) {
    $scope.precedingCount[i] = $scope.precedingCount[i-1] + $scope.data[i-1].length
  }

  $scope.combinedIndex = function(oIndx, iIndx) {
    return $scope.precedingCount[oIndx] + iIndx
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myController">
  <div ng-repeat="list in data track by $index" ng-init="outerIndex = $index">
    <div id="{{combinedIndex(outerIndex, $index)}}" ng-repeat="listChild in list track by $index">
        {{listChild}} - {{counter}} - {{outerIndex}} - {{$index}} - {{combinedIndex(outerIndex, $index)}}
    </div>
  </div>

  <br />
  <br />
  
  <div>
    The count of the previous indices: {{precedingCount}}
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用保留listChild

数量的外部变量
<div ng-repeat="list in [[1,2,3,4], [1,2,3,4]] track by $index">
    <div id="{{counter}}" ng-repeat="listChild in list track by $index" ng-init="counter += 1">
        {{listChild}}
    </div>
</div