knockout foreach add row number to grid

397 views Asked by At

I have this grid that fills an array within an array. It creates according to one array and then fills that column with another array.

Like

 <div id="formula" data-bind="with:currentFormula">
        <!-- ko foreach:$parent.tones-->
        <div class="col-sm-2" data-bind="foreach:$parents[1].levels">
            <a href="#" class="thumbnail img-responsive" data-bind="click: $root.hasCurrent() ? $root.currentFormula().setEnding.bind($index(),$parentContext.$index())  : $root.currentFormula().setStarting.bind($index(),$parentContext.$index())">
                <img data-bind="attr:{ src: '/Content/images/colors/' +  $index() +  $parentContext.$index() + '.png' }" alt="" />
            </a>
        </div>
        <!-- /ko-->
    </div>

What I need to do is create a new column before col 1 and add the $index() + 1, or row number would work to that column.

I've looked all over and have not found anything that works.

How would I do this?

1

There are 1 answers

0
BateTech On BEST ANSWER

From what I can tell, your rows are being created based on currentFormula.tones within <!-- ko foreach:$parent.tones--> and columns based on tones.levels. So you should create a div that binds its text to $index() + 1 only if the first level (column). To do this, you will need to move your loop for creating columns up above the div that will represent the column.

Something like this:

<div id="formula" data-bind="with: currentFormula">
    <!-- ko foreach:$parent.tones-->
        <!-- ko foreach:$parents[1].levels -->
            <!-- If this is the first level/column, then create a new column to show rownum  -->
            <div class="col-sm-2" data-bind="if: $index() == 0, text: 'Row ' + $parent.$index() + 1"></div>
            <!-- Normal column creation -->
            <div class="col-sm-2" >
                <a href="#" class="thumbnail img-responsive" data-bind="click: $root.hasCurrent() ? $root.currentFormula().setEnding.bind($index(), $parentContext.$index()) : $root.currentFormula().setStarting.bind($index(), $parentContext.$index())">
                    <img data-bind="attr: { src: '/Content/images/colors/' + $index() + $parentContext.$index() + '.png' }" alt="" />
                </a>
            </div>
        <!-- /ko-->
    <!-- /ko-->
</div>