Create a new line every 2 entries using foreach knockout

I am trying to create a new line every two records using virtual knockout elements. My problem is that the odd record is not generated between two even indices.

Here is my original HTML

<!--ko foreach:UDGroupboxes--> <!--ko if:$index()%2==0 || $index()==0--> <div class="row-fluid"> <!--/ko--> <div class="panel form-horizontal span6"> <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div> </div> <!--ko if:$index%2()!=0 && $index()!=0--> </div> <!--/ko--> <!--/ko--> 

HTML output

 <div data-bind="attr:{id:Name}" class="tab-pane active" id="Tabsheet1"> <!--ko foreach:UDGroupboxes--> <!--ko if:$index()%2==0 || $index()==0--> <div class="row-fluid"> <!--/ko--> <div class="panel form-horizontal span6"> <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div> </div> <!--ko if:$index%2()!=0&&$index()!=0--> </div> <!--/ko--> <!--ko if:$index()%2==0 || $index()==0--><!--/ko--> <!--ko if:$index()%2==0 || $index()==0--> <div class="row-fluid"> <!--/ko--> <div class="panel form-horizontal span6"> <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div> </div> <!--ko if:$index()%2!=0&&$index()!=0--> </div> <!--/ko--> <!--/ko--> </div> 

The panel should be created regardless of the condition. The condition determines only the opening of a new line on even numbers and the closing of the line by chances.

+4
source share
2 answers

Knockout binding occurs only with elements, and virtual elements must also adhere to the hierarchy of elements. If we take your example and indent to show the relation of an element, it looks like this:

 <!--ko foreach:UDGroupboxes--> <!--ko if:$index()%2==0--> <div class="row-fluid"> <!--/ko--> <div class="panel form-horizontal span6"> <div class="panel-heading"><span data-bind="text:$data.Caption"></span></div> </div> <!--ko if:$index()%2!=0--> </div> <!--/ko--> <!--/ko--> 

Closing and opening virtual tags in a div ignored by knockout. Thus, the above simply leads to the conclusion of each other element.

Here is a good answer for grouping array elements in Knockout: fooobar.com/questions/591776 / ...

+8
source

You are better off knocking out a multidimensional array. This is a much cleaner solution and has less potential for fancy results.

See example 2: note 3: in the documentation: http://knockoutjs.com/documentation/foreach-binding.html

 <ul data-bind="foreach: { data: categories, as: 'category' }"> <li> <ul data-bind="foreach: { data: items, as: 'item' }"> <li> <span data-bind="text: category.name"></span>: <span data-bind="text: item"></span> </li> </ul> </li> </ul> <script> var viewModel = { categories: ko.observableArray([ { name: 'Fruit', items: [ 'Apple', 'Orange', 'Banana' ] }, { name: 'Vegetables', items: [ 'Celery', 'Corn', 'Spinach' ] } ]) }; ko.applyBindings(viewModel); </script> 
0
source

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


All Articles