Angularjs在嵌套的ng-repeat中递增计数

时间:2014-12-02 10:41:37

标签: angularjs ng-repeat

我的情况是我想在嵌套的ng-repeat

上维护一个计数器
<ul>
    <li ng-repeat="some in something">
        <span> index {{someCounter}} </span>
        <ul>
            <li ng-repeat="chid in some">
                <span> index {{someCounter}} </span>
            </li>
        </ul>
    </li>
</ul>

应该在

之后输出
  • 索引0
    • index 1
    • index 2
  • index 3

简而言之,不是每个ng-repeat都有单独的索引,我想让每个ng-repeat继续使用相同的索引

由于

2 个答案:

答案 0 :(得分:0)

我知道没有简单的方法来实现这一目标。您需要做的是预处理正在重复的对象并以循环方式为其分配计数器。我想不出单凭HTML的方法。另外,我不认为这适用于数组,这是我的尝试:

假设您会在某个时刻对对象进行排序,以便按顺序显示:

$scope.something = [
      {one: {ten: 10}, eleven: {nine: 9}, hundred: {blue: 100}}, 
      {one: {ten: 10}, eleven: {nine: 9}, hundred: {blue: 100}}, 
      {one: {ten: 10}, eleven: {nine: 9}, hundred: {blue: 100}}, 
      {one: {ten: 10}, eleven: {nine: 9}, hundred: {blue: 100}}, 
      {one: {ten: 10}, eleven: {nine: 9}, hundred: {blue: 100}}, 
      ];

var counter = 0;
angular.forEach($scope.something, function(value, index){
  //console.log(value); 
  value.counter = counter++;

  angular.forEach(value, function(subValue, subIndex){
    //console.log(subValue); 
    subValue.counter = counter++; 
  });

});
console.log($scope.something);

HTML:

<ul >
    <li ng-repeat="some in something" > 
        <span > index {{some.counter}}</span>
        <ul>
            <li ng-repeat="(key, child) in some" ng-if="key != 'counter'" > 
                <span> index {{child.counter}} </span>
            </li>
        </ul>
    </li>
</ul>

Plunker:http://plnkr.co/edit/98AnSbO2fpdsFuo3hVCz?p=preview

答案 1 :(得分:0)

在嵌套的ng-repeat上维护单独的计数器很容易。

您可以使用以下语法在嵌套的ng-repeat中获取计数器(col)。虽然仍需要按$ index跟踪,但由于你有计数器,所以你不需要在逻辑中使用它。

ng-repeat="(col, t) in h.seats track by $index"

我有一个数组,我想将其转换为列大小为4的网格/矩阵。以下实现对我有用。您可以在嵌套的ng-repeat

旁边使用两个计数器:row和col
        <tbody>
            <tr ng-repeat="(row, y) in getNumber(h.seats.length, 3) track by $index">
                <td>{{row+1}}</td>
                <td class="text-primary" ng-class="appliedClass(!t.status)"
                    ng-repeat="(col, t) in h.seats track by $index"
                    ng-if="col >= (row)*3 && col < (row+1)*3">
                        <span ng-show="t.status"> X </span> 
                        <span ng-show="!t.status"> - </span>
                </td>
            </tr>
        </tbody>

有关计数器如何工作的详细信息,请访问https://stackoverflow.com/a/35566132/5076414