user2355793 user2355793 - 13 days ago 15
Javascript Question

Knockout foreach dynamically set ID

I just started using knockout and having some problems using foreach.
I need to dynamically populate a list with "collapsing" div.
I cant figuer out how to set the
"data-target=""" with the according div id.Is there a kind of $index as in Angular.How do i declare it inside of the data-target?

Thank for the help.

<ul class="nav navbar-nav side-nav">
<li data-bind="foreach: { data: categories, as: 'category' }">
<a href="javascript:;" data-toggle="collapse" data-target="??" data-bind="text: category.title"> </a>
<div id="??" class="collapse">
<h1>Some text</h1>
</div>
</li>
</ul>

Answer

Do it within the data-bind:

<a href="javascript:;" data-toggle="collapse"  data-bind="attr: { 'data-target': ... }">
  <div class="collapse" data-bind="attr: { id: ... }">

Knockout does have a $index context property, too:

<div data-bind="attr: { id: 'foo' + $index() }">