Kyrre
Kyrre

Reputation: 698

AngularJS - track inner $index across multiple ng-repeat loops

I'm attempting to list out a nested data structure while maintaining the inner $index as a running index.

To illustrate, this is what I want to achieve:

Category Name 1
    1. Foo
    2. Bar
    3. Fez

Category Name 2
    4. Qux
    5. Baz

And this is the result I get now:

Category Name 1
    1. Foo
    2. Bar
    3. Fez

Category Name 2
    1. Qux
    2. Baz

As you can see, I'd like for the index to carry over between parent loops. A simple problem to solve in regular programming, but it's proving a bit difficult to do in the angularjs loops themselves.

Here is a boiled-down version of what is currently running, the custom number property on the li element being the tricky bit.

<div ng-repeat="(category, items) in groups">
    <h2 class="category-name">{@ category @}</h2>
    <ul class="items-list">
        <li id="{@ item.id @}" my-widget ng-repeat="item in items" number="$index">
        </li>
    </ul>
</div>

The data is structured as such (the boiled-off code consumes the objects):

{
  'Category Name 1': [{id:1},{id:2}],
  'Category Name 2': [{id:3},{id:4}]
}

Note that there is no guarantee that the ids will/should be sequential.

I've attempted to use a scope variable and attempted to increment it in the loop, but it always shows as the last number:

// Controller.js
$scope.count = 0

// view.html
<li ... number="count + 1"></li> <!-- or count++ or any obvious variation -->

Or even something as ugly as:

... </li>
<p hidden>{@ increment() @}</p>

// Controller.js
$scope.increment = function(){$scope.count++;};

In addition, these just make AngularJS explode with error messages regarding $apply.

I've also attempted to use ng-init in the parent loop to store the loop index, but I must be misunderstanding how to use it properly. Apologies for not showing any more work, but I'm having trouble getting anywhere other than where I am..

What can I do to carry over the loop?

Any help would be greatly appreciated!

Upvotes: 0

Views: 376

Answers (1)

Petr Averyanov
Petr Averyanov

Reputation: 9476

Add global index property to item and calculate it. Or if you dont want to change item object create it as map:

$scope.myIndexMap = {};
globalIndex = 0;
forEach..., forEach...
  globalIndex++;
  $scope.myIndexMap[item.id] = globalIndex;

P.S. lots of people tries to do weird and complicated things in html -- better do not. View should be as simple as possible.

Upvotes: 1

Related Questions