【问题标题】:Knockout nested foreach with templates not working as expected使用模板无法按预期工作的淘汰嵌套 foreach
【发布时间】:2013-03-08 14:56:37
【问题描述】:

我尝试做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 部分。

我做错了什么?

【问题讨论】:

  • 不,我没有收到任何错误。

标签: javascript jquery knockout.js jquery-templates


【解决方案1】:

databind="template[...]",应该是data-bind ;)

【讨论】:

  • 很容易被忽略,事实上我还是得运行它才注意到。 :)
  • 我在 jsFiddle 中完全重写了大部分内容,但仍然没有抓住它!
  • static.divbyzero.nl/facepalm/doublefacepalm.jpg - 实际上我只是来删除这个问题,因为我自己发现了它......
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 2018-03-01
相关资源
最近更新 更多