Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$index+1 in Knockout foreach binding

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>

like image 894
Sanchitos Avatar asked Jul 18 '13 21:07

Sanchitos


People also ask

For what purpose do we use foreach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.

How to get index in knockout js?

Knockout provides a better way to access the index of items in an array, whether it is a normal array or an observable array. The syntax $index / $index() provides the way to access the index of the current item in the array. But its value is only accessible within the context of the foreach block.

What is binding in knockout?

Essentially a binding or a data binding is a way to link your ViewModels to your Views(templates) and vice versa. KnockoutJS uses two-way data binding, which means changes to your ViewModel influence the View and changes to your View can influence the ViewModel.


1 Answers

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

<span data-bind="text: ($index() + 1)"> </span> 
like image 60
Damien Avatar answered Sep 21 '22 16:09

Damien