问题
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?
回答1:
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>
回答2:
The following will do it:
<!-- ko template: { name: 'template-name', data: vm } --> <!-- /ko -->
回答3:
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>
来源:https://stackoverflow.com/questions/9276719/knockout-template-binding