$index+1 in Knockout foreach binding

风格不统一 提交于 2019-12-31 08:42:33

问题


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>


回答1:


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

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



回答2:


I found the answer here: Knockout is not evaluating an expression when using $index in a binding

In order to use it <span data-bind="text: $index() + 1"></span>



来源:https://stackoverflow.com/questions/17734415/index1-in-knockout-foreach-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!