Knockout does not evaluate expression when using $ index in binding

Why is this, when I try to use knockout.js to bind some text with $ index, I get the function code instead of a number?

<tbody data-bind="foreach: MyList"> <tr> <td><span data-bind="text: $index + 1"></span></td> </tr> </tbody> 

Instead of getting 1, 2, 3, etc. I get the following:

enter image description here

You can see from the last character in the image above that my zero index is added to 1. If I remove '+ 1' from my binding, I get 0, 1, 2 instead of a function.

How to report a knockout to evaluate the expression? I have the same problem when I submit a form. My string fields are passed as a function instead of a value.

+14
Jul 02 2018-12-12T00:
source share
2 answers

$ index is observable, which is a function. Try <span data-bind="text: $index() + 1"></span>

+31
Jul 02 '12 at 23:11
source share
— -

If you use

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

and for example, your index value is 2, the text of your range will be: 21, not 3.

you must define a function in your view of the Mode, for example:

 self.itemNumber = function(index) { return index + 1; } 

and then in your range you should do:

 <span data-bind="text: $root.itemNumber($index())"></span> 

Hope this helps :)

+4
Feb 06 '13 at
source share



All Articles