Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last iteration of foreach data-bind in knockout js

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.

like image 742
Govan Avatar asked Dec 02 '22 20:12

Govan


2 Answers

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/

like image 180
RP Niemeyer Avatar answered Dec 29 '22 00:12

RP Niemeyer


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>
like image 29
Damien Avatar answered Dec 28 '22 22:12

Damien