How to use foreach with a special first element ?

How to use foreach with a special first element ?

Asked on December 1, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

    It is possible by using  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>
    

       Have a look at this link : http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/

    Answered on December 1, 2018.
    Add Comment

        Now there is no way  to tell the template binding where to provide the template, This method will work:

    <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, 1st give the first item in the array as templateOptions and checking for if the item that we are dealing with in the template is indeed the first.

        See this example : http://jsfiddle.net/rniemeyer/XuXcr/

      Also templateOptions was added after 1.12 KO, so The current code is wanted. More info about templateOptions here..

    Answered on December 1, 2018.
    Add Comment

       For use the foreach with a special first element, Try this code:

    <!-- ko if: $index() == 0 -->
    your code
    <!-- /ko -->
    
    Answered on December 1, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.