简体   繁体   中英

Nested foreach in knockout.js

I can't seem to get a nested foreach to work.

JS code is:

$(document).ready(function() {

    function chartValueViewModel(date, price) {
        this.date = date;
        this.price = price;
    }

    function chartViewModel(id, name, lineType, values) {
        this.id = id;
        this.name = name;
        this.lineType = lineType;
        this.values = ko.observableArray(values);
    }

    function liveCurveViewModel() {

        this.chartsData = ko.observableArray([]);
        var chartsData = this.chartsData;

        this.init = function() {

            var mappedCharts = $.map(chartValues,
            function(chart) {
                var mappedValues = $.map(chart.chartValues, function(value) {
                    return new chartValueViewModel(value.dateTime, value.price);
                })
                return new chartViewModel(chart.id, chart.name, chart.liveCurveTypeId, mappedValues);
            });

            chartsData(mappedCharts);
        };
    }

    var vm = new liveCurveViewModel();
    vm.init();
    ko.applyBindings(vm);

});

Html is:

<ul data-bind="foreach: chartsData ">
    <li data-bind="text: name">
        <ul data-bind="foreach: values">
           <li data-bind="text: price">
           </li>
        </ul>
    </li>
</ul>

The outside loop renders correctly, but I get nothing from the inside loop, not even an error message. I've checked and the values field on the chartViewModel is populated.

The text binding that you have on your outside li is overwriting the content inside of it, so it is blowing away your inner foreach . The text binding sets the innerText/textContent of the element, which overwrites the current children.

You would want to do something like:

<ul data-bind="foreach: chartsData ">
    <li>
        <span data-bind="text: name"></span>
        <ul data-bind="foreach: values">
           <li data-bind="text: price">
           </li>
        </ul>
    </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM