How to use foreach with a special first element?

安稳与你 提交于 2019-12-12 07:17:05

问题


If I have an observable array

foos = [{ name: "a" }, { name: "b" }, { name: "c" }]

on my viewmodel, I would like to render the following:

<ul>
  <li class="add-new-foo">Special stuff here</li>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

I got pretty close with

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

But this ended up putting the .add-new-foo after the a, b, c.

Any ideas? In my case it's crucial to use Knockout foreach instead of jQuery template's {{each}}, because of the benefits mentioned in the Knockout docs.


回答1:


Looks like it's going to be possible with the new containerless control flow and foreach binding in KO 1.3 2.0:

<ul>
    <li>Static item</li>
    <!-- ko foreach: products -->
        <li data-bind="text: name"></li>
    <!-- /ko -->
</ul>

See this post for details: http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/




回答2:


As there is not currently a way to tell the template binding where to render the template, I don't see a cleaner way to do it right now other than something like:

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

So, we are passing the first item in your array as templateOptions and checking for if the item that we are dealing with in the template is indeed the first.

Sample here: http://jsfiddle.net/rniemeyer/XuXcr/

Also templateOptions was added after 1.12 KO, so you would need current code. More info about templateOptions here.

Hope this helps.




回答3:


<!-- ko if: $index() == 0 -->
your code
<!-- /ko -->



回答4:


This:

<ul>
    <li>Static item</li>
    <!-- ko foreach: products -->
        <li data-bind="text: name"></li>
    <!-- /ko -->
</ul>

will not work in IE8. I'm leaning toward the template answer for that situation. Any other ideas?

EDIT: here is what worked in IE8 - knockout 2.2.1: using the options bindings as per the bottom of the following comment:

https://stackoverflow.com/a/16361750



来源:https://stackoverflow.com/questions/5371772/how-to-use-foreach-with-a-special-first-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!