JL.
JL.

Reputation: 81342

How to get a count going inside a Knockout foreach loop?

I have a standard foreach, and the loop is working correctly:

<!-- m7ko foreach: MyCollection -->
   <div id="panel1" />
<!-- /m7ko -->

Just to simplify, all I want to do is change the static id's of panel1 to panel1, panel2, panel3, etc as it loops.

Upvotes: 1

Views: 1550

Answers (1)

rwisch45
rwisch45

Reputation: 3702

You could use the $index and the attr binding. Something like this

<div data-bind='attr: { id: 'panel' + $index() + 1 }'></div>

where $index is the current position of that element in the KO observable array.
It's probably cleaner to put that in a computed observable though, but the logic is pretty much the same.

Upvotes: 6

Related Questions