Is there a way to find last iteration using foreach data-bind in knockout js?
My problem is, I am iterating over a list of items and want to print all items separated by a line.
I don't want to draw a line(hr) for the last item of that array.
Inside of a foreach, you can bind against a special context variable (observable) called $index
. So, you could bind something like visible: $index() < $parent.items().length - 1
.
Sample: http://jsfiddle.net/rniemeyer/M55qh/
You can check if you are displaying the first element.
<div data-bind="foreach: items">
<hr data-bind="visible : $index()!=0" />
<span data-bind="text: $data"></span>
</div>
See fiddle
Or as RP Niemeyer said, you can omit the last hr :
<div data-bind="foreach: items">
<span data-bind="text: $data"></span>
<hr data-bind="visible : $index() != ($parent.length-1)" />
// notice the hr is after the item.
</div>
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