Working with Knockout 'foreach' looping through multidimensional array

前端 未结 3 1000
粉色の甜心
粉色の甜心 2021-01-13 12:59

I have a multidimensional associative array.

this.items = ko.observableArray([
    { name: \"name1\", viewable: true, children: [
        { name: \"name1-1\"         


        
相关标签:
3条回答
  • 2021-01-13 13:50

    If you add empty children arrays on items you can use template

    JSFiddle sample

    <ul data-bind="foreach: items">
        <idv data-bind="template: {name: 'mytemp'}" />
    </ul>
    <div data-bind="stopBinding:true">
        <div id="mytemp">
            <div data-bind="visible :viewable">
                <li data-bind="text: name"></li>
                <div data-bind="foreach: children">
                    <div data-bind="template: {name: 'mytemp'}" /></div>
            </div>
        </div>
    </div>
    
    0 讨论(0)
  • 2021-01-13 13:52

    What you need is a template:

    <script type="text/html" id="ItemTemplate">
        <!-- ko if: viewable -->
            <li data-bind="text: name"></li>
            <!-- ko template: { name: 'ItemTemplate', foreach: children } --><!-- /ko -->
        <!-- /ko -->
    </script>
    

    And then just:

    <ul data-bind="template: { name: 'ItemTemplate', foreach: items }"></ul>
    
    0 讨论(0)
  • 2021-01-13 13:54

    Underscore.js has some nice method working with arrays maybe you can use flatten and filter to create one array from your structure then you can just write one foreach:

    Or you could use templates to encapsulate your if: viewable logic and apply the template recursively:

    <script type="text/html" id="template">
      <!-- ko if: viewable -->
        <li data-bind="text: name"></li>    
            <!-- ko template: { name: 'template', foreach: $data.children } -->
            <!-- /ko -->    
      <!-- /ko -->
    </script>
    
    <ul data-bind="template: { name: 'template', foreach: items } ">
    </ul>
    

    Demo JSFiddle.

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