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>
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.
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.
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.
$index is an observable. So you need to use it this way :
<span data-bind="text: ($index() + 1)"> </span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With