15

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.

1 Answer 1

35

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>
Sign up to request clarification or add additional context in comments.

2 Comments

@RP Niemeyer u should explain why outer li text binding overwrite the inner one. if possible explain this behavior in details. thanks
@Thomas - added an additional sentence to clarify that the text binding sets innertText/textContent. Hope that helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.