如何使用具有特殊第一元素的foreach?

Dom*_*nic 18 jquery-templates knockout.js

如果我有一个可观察的数组

foos = [{ name: "a" }, { name: "b" }, { name: "c" }]
Run Code Online (Sandbox Code Playgroud)

在我的viewmodel上,我想呈现以下内容:

<ul>
  <li class="add-new-foo">Special stuff here</li>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我非常接近

<ul data-bind="template: { name: 'foo-template', foreach: foos }">
  <li class="add-new-foo">Special stuff here</li>
</ul>

<script id="foo-template" type="text/html">
  <li data-bind="text: name"></li>
</script>
Run Code Online (Sandbox Code Playgroud)

但最终把a,b,c 放在了.add-new-foo 后面.

有任何想法吗?在我的情况下,使用Knockout foreach而不是jQuery模板是至关重要的{{each}},因为Knockout文档中提到的好处.

Jac*_*cob 39

foreach在KO 1.3 2.0中使用新的无容器控制流和绑定看起来是可能的:

<ul>
    <li>Static item</li>
    <!-- ko foreach: products -->
        <li data-bind="text: name"></li>
    <!-- /ko -->
</ul>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此帖子:http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/


RP *_*yer 10

由于目前没有办法告诉模板绑定在哪里渲染模板,我现在没有看到更清晰的方法,除了以下内容:

<ul data-bind="template: { name: 'foo-template', foreach: foos, templateOptions: { first: foos()[0]} }">
</ul>

<script id="foo-template" type="text/html">
    {{if $item.first === $data}}
    <li class="add-new-foo">Special stuff here</li>
    {{/if}}
    <li data-bind="text: name"></li>
</script>
Run Code Online (Sandbox Code Playgroud)

因此,我们将数组中的第一个项目作为templateOptions传递,并检查我们在模板中处理的项目是否确实是第一项.

此处示例:http: //jsfiddle.net/rniemeyer/XuXcr/

此外,在1.12 KO之后添加了templateOptions,因此您需要当前的代码.有关templateOptions更多信息在这里.

希望这可以帮助.