Adrian Oceguera
Adrian Oceguera

Reputation: 91

Knockout Template in foreach access specific template item

I am populating a list of survey questions. On click of a survey question, a modal with graphs of the results pop up. To create my list I am using a knockout template as I need the afterRender function.

Here's my markup:

<div id="priorityMenuW" class="priorityMenuW shadow">
    <div class="menuHeader">Select a Survey Question:</div>
    <div id="priorityMenu" data-bind="foreach:questionTypes">
        <div class="menucategory menuItem" data-toggle="tooltip" data-bind="text:CategoryName, attr:{title:CategoryName}"></div>
        <div class="menuitem" data-toggle="tooltip" data-bind="foreach:$root.questions">
            <!-- ko if: CategoryName == $parent.CategoryName-->
            <div data-bind='template: { name: "question-template",
                                        data:$root.questions,
                                        afterRender: $root.storeQuestionIdOrder }'>
            </div>
            <!-- /ko -->
        </div>
    </div>
</div>

And my template:

<code><script type="text/html" id="question-template">

<div class="menuItem" data-toggle="tooltip" data-bind="html:'&bull; '+ $parent.QuestionText, attr:{title:$parent.QuestionText}, css: {'itemSelected' : $root.isPriorityActive($data)}, click: function($data,event){$root.questionChoice($data,event)}"></div></script></code>

My problem is that by sending $data to the function questionChoice, I am receiving an array of all of the templated objects. How can I access the specific object clicked on? I was thinking maybe $data[$index], but that doesn't work.

Upvotes: 1

Views: 373

Answers (1)

dfperry
dfperry

Reputation: 2258

if you want to use $data[$index], remember that $index is an observable and needs to be evaluated:

$data[$index()]

Upvotes: 1

Related Questions