$parentContext.$index is not defined in Knockout.j

2019-07-20 03:01发布

问题:

I am looping through the data and trying to create runtime html I am unable to fetch the index from the collection, I m using knockout-2.1.0.js. Am I doing something wrong?

<ul data-bind="foreach: gridOptions.columns">    
    <li>     
        <label data-role="none" data-bind="attr:{for: 'chk' + $parentContext.$index }">     
        </label>
        <input type="checkbox" data-bind="attr:{ id: 'chk' + $parentContext.$index }, checked: checked}" /><span data-bind="text:header"></span>
    </li>    
</ul>

Viewmodel is gridOptions:

{
    columns: [{
        header: 'Catalog Number',
        dataMember: 'productName',
        checked: ko.observable(true)
    }, {
        header: 'Description',
        dataMember: 'shortDesc',
        checked: ko.observable(true)
    }]
},

Please help me on this as I am stuck with this. I have tried with plain $index or $index() every possible thing but couldn't make this work.

回答1:

data-bind="attr: { 'for': 'chk' + $index() }"
Remove }:
data-bind="attr: { 'id': 'chk' + $index() }, checked: checked"

Working example: http://jsfiddle.net/myS95/3/.



回答2:

It works if you have nested arrays

http://jsfiddle.net/AXvxR/



标签: knockout.js