Why is it, that when I try to use knockout.js to bind some text using $index, I get the code of a function 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 this:
You can see, by the last character in the above image, that my index of zero is being added to 1. If I remove the '+ 1' from my binding, I get 0, 1, 2 instead of the function.
How do I tell knockout to evaluate the expression? I have the same issue when I submit the form. My string fields are being submitted as a function instead of the value.
This binding is used to bind the child elements of an object in the specified object's context. This binding can also be nested with other type of bindings such as if and foreach. Syntax with: <binding-object> Parameters. Pass the object which you want to use as context for binding child elements as the parameter.
In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.
Knockout. js defines an important role when we want to detect and respond to changes on one object, we uses the observable. An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted.
$index is an observable, which is a function. Try <span data-bind="text: $index() + 1"></span>
If you use
<span data-bind="text: $index() + 1"></span>
and for example your index value is 2, the text of your span will be: 21 and not 3.
you should define a function in your viewModel, like this:
self.itemNumber = function(index) {
return index + 1;
}
and then in your span you should do:
<span data-bind="text: $root.itemNumber($index())"></span>
I hope this will help :)
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