$index+1 in Knockout foreach binding

Sanchitos picture Sanchitos · Jul 18, 2013 · Viewed 25.8k times · Source

I need to display $index+1 in a table.

If I just use the $index all the elements will start from 0, I need to start at 1.

Here's the documentation of knockout: http://knockoutjs.com/documentation/foreach-binding.html

In there you can find this example:

<h4>People</h4>
<ul data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>
<button data-bind="click: addPerson">Add</button>

So it will display the following:

People

Name at position 0: Bert Remove

Name at position 1: Charles Remove

Name at position 2: Denise Remove

I really need this to be just for display purposes.

Name at position 1: Bert Remove

Name at position 2: Charles Remove

Name at position 3: Denise Remove

I tried this without success <span data-bind="text: ($index + 1)"> </span>

Answer

Damien picture Damien · Jul 18, 2013

$index is an observable. So you need to use it this way :

<span data-bind="text: ($index() + 1)"> </span>