Find last iteration of foreach data binding in js knockout

Is there a way to find the last iteration using foreach data-bind in js knockout?

My problem: I repeat the list of elements and want to print all the elements separated by a string.

I do not want to draw a string (hr) for the last element of this array.

+4
source share
4 answers

You can check if the first item is displayed.

<div data-bind="foreach: items">
   <hr data-bind="visible : $index()!=0" /> 
   <span data-bind="text: $data"></span>
</div>

See violin

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>
+6
source

foreach (), $index. , - visible: $index() < $parent.items().length - 1.

: http://jsfiddle.net/rniemeyer/M55qh/

+8

With CSS, maybe you can use last-childtry:

hr:last-child {
  display:none;
}

And if you can be more specific, for example, add a idparent container.

+3
source

Could you use visible: $index() < list().lengthor something like that?

http://jsfiddle.net/x2aa7/

0
source

Source: https://habr.com/ru/post/1523913/


All Articles