Create new row every 2 records using knockout foreach

后端 未结 2 972
旧巷少年郎
旧巷少年郎 2021-01-06 03:53

I\'m attempting to create a new row every two records using knockout virtual elements. My problem is that the odd record does not generate in between the two even indexes.

相关标签:
2条回答
  • 2021-01-06 04:11

    You're better off supplying knockout with a multi-dimensional array. This is a much cleaner solution and has less potential for quirky results.

    Look at 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 讨论(0)
  • Knockout binding only happen on elements, and virtual elements must also adhere to the element hierarchy. If we take your example and use indentation to show the element relation, 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-->
    

    The closing and opening virtual tags within the div are ignored by Knockout. So the above just has the effect of outputting every other item.

    Here is a good answer for doing grouping of array items in Knockout: https://stackoverflow.com/a/10577599/1287183

    0 讨论(0)
提交回复
热议问题