knockout template binding

2020-07-15 03:43发布

I have an ul element which is filled through template binding.

<script type="text/html" id="someTemplate">
<li>
   <span data-bind="text: someText">
</li>
</script>

<ul data-bind="template: {foreach: someElemets, name: 'someTemplate'}">
</ul>

But I want the first li-tag would not be li-tag from template but another one with button in it and it will not be connected to someElemets array. If I do in that way

<ul data-bind="template: {foreach: someElemets, name: 'someTemplate'}">
    <li><button data-bind=click: doSomething">Click me</button></li>
</ul>

then li-tag with button will be the last one after rendering. What is the best way to solve that problem?

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-15 04:00

You can use containerless control flow syntax, databinding using comment tags. No need for a template. more info

<ul>     
    <li><button data-bind=click: doSomething">Click me</button></li>
    <!-- ko foreach: someElemets-->         
    <li>
        <span data-bind="text: someText"></span>
    </li>    
    <!-- /ko -->
</ul> 
查看更多
狗以群分
3楼-- · 2020-07-15 04:08

I'm not aware of an easy way to access the index when inside a template. You could use template options as described at How to use foreach with a special first element?

Your code would be something like:

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

<script id="someTemplate" type="text/html">
    <li>
    {{if $item.first === $data}}
      <button data-bind="click: doSomething">Click me</button>
    {{/if}}
    <span data-bind="text: someText">
    </li>
</script>
查看更多
Rolldiameter
4楼-- · 2020-07-15 04:16

The following will do it:

<!-- ko template: { name: 'template-name', data: vm } --> <!-- /ko -->
查看更多
登录 后发表回答