Knockout嵌套的foreach模板不能按预期工作

时间:2013-03-08 14:56:38

标签: javascript jquery knockout.js jquery-templates

我试图做jsFiddle,但它抱怨模板脚本,但下面是一个完整的例子,你可以放入.html文件并在本地查看。

<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>

我期望的输出是:

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

但输出中缺少- Inner 1 Name篇。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

databind =“template [...]”,应为 data-bind ;)