Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 592
mat-mcloughlin Avatar asked Jun 06 '12 21:06

mat-mcloughlin


1 Answers

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>
like image 121
RP Niemeyer Avatar answered Oct 15 '22 18:10

RP Niemeyer