• Knockout pattern binding

    I have an ul element that is populated by 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 to not be the li tag from the template, and the other with a button in it, and it will not be associated with someElemets array. If i do that

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

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

    +5
    source share
    3 answers

    You can use control flow syntax without a container, data binding using comment tags. No template needed. more details

    <ul>     
        <li><button data-bind=click: doSomething">Click me</button></li>
        <!-- ko foreach: someElemets-->         
        <li>
            <span data-bind="text: someText"></span>
        </li>    
        <!-- /ko -->
    </ul> 
    
    +11
    source

    This will do the following:

    <!-- ko template: { name: 'template-name', data: vm } --> <!-- /ko -->
    
    +7
    source

    I do not know how easy it is to access the index inside the template. You can use the template options as described in How to use foreach with a special first element?

    Your code will look something like this:

    <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>
    
    +1
    source

    All Articles