Search code examples
javascriptjqueryknockout.jsjquery-templates

Knockout nested foreach with templates not working as expected


I tried to do jsFiddle, but it complained about the template script, but below is a complete example you can put into a .html file and view locally.

<html>
<head>
<title>Test</title>

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<script type="text/javascript">

var InnerModel = function() {
    this.name = ko.observable("");
}

var OuterModel = function() {
    this.name = ko.observable("");
    this.innerItems = ko.observableArray();
}

var ViewModel = function() {
    this.name = ko.observable("");
    this.outerItems = ko.observableArray();
}

$(document).ready(function() {

    var model = new ViewModel();
    ko.applyBindings(model)

    model.name("ModelName");
    outerItem = new OuterModel();
    outerItem.name("Outer 1 Name");
    model.outerItems.push(outerItem);
    innerItem = new InnerModel();
    innerItem.name("Inner 1 Name");
    outerItem.innerItems.push(innerItem);
});
</script>

</head>
<body>
<script type="text/html" id="inner-template">    
    <li><span data-bind="text: inner.name"> </span></li>
</script>

<h3>Model Name: <span data-bind="text: name"></span></h3>

<div data-bind="foreach: outerItems" >
    <h4><b>Outer:</b> <span data-bind="text: name"></span></h4> 
    <ul databind="template: { name: 'inner-template', foreach: innerItems, as: 'inner' }" ></ul>
</div>

</body>
</html>

The output I would expect is:

Model Name: ModelName
Outer: Outer 1 Name
- Inner 1 Name

But the - Inner 1 Name piece is missing from the output.

What am I doing wrong?


Solution

  • The databind="template[...]", should be data-bind ;)