zach
zach

Reputation: 802

knockout js foreach not working with child collection

I have a a model I'm mapping from json data that basically contains a list of categories, and within each category, is a list of controls... So, in my UI I have a panel with a list of the categories and when the user clicks it, I'm pushing the entire category to a (at load time) empty observable to render in a another panel... the click function seems to be working but nothing is rendering in my 2nd column using the foreach statement. Any help would be appreciated. My json data is a bit lengthy so it may be best to refer to my fiddle here:

http://jsfiddle.net/TU3ps/4/

But here is my how I'm trying to foreach the child, is my syntax bad here?

        <div class="left">Click any of the below categories to see its controls...
            <ul data-bind="foreach:  Categories">
                <li data-bind="click:  $parent.catClick"> 
                    <span data-bind="text:  Text"></span>
                </li>
            </ul>
        </div>
        <div class="right">Controls within the category clicked...
            <ul data-bind="foreach:  Curr.Ranges">
                <li>
                    <span data-bind="text:  FieldName" />
                </li>
            </ul>
        </div>

Is there a better way I should be doing this? Basically, I want my right panel to show only one collection at a time. All I'm trying to do right now is display the fieldname but nothing is showing up. Any help would be greatly appreciated....

Upvotes: 0

Views: 777

Answers (1)

Paul Manzotti
Paul Manzotti

Reputation: 5147

It looks as if you want Curr to be an observable, not an observableArray, and you're not assigning it correctly:

viewModel.Curr = ko.observable();
// Inside your click method
viewModel.Curr(category);

You also need to add in a dummy property of Ranges, otherwise knockout blows up on the initial applyBindings:

viewModel.Curr = ko.observable({ Ranges: [] });

Upvotes: 1

Related Questions