1

I have the following code:

<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>

I want to make counter be the number of the element but relative to the whole parent array. How can I make it work so the divs count continuously and not as two individual arrays. to be something like this:

<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 Answers 2

1

The code below accounts for varied array lengths within the parent array. $scope.precedingCount tracks the rolling total up to the start of a given inner array

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
  }
});
<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>

Sign up to request clarification or add additional context in comments.

Comments

0

You could use an external variable that will keep the number of 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

2 Comments

Looks correct at first but it will not work anyway due to how ngInit works ;)
Yup, it doesnt work, I've tried that before, thanks for the suggestion though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.