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

。_饼干妹妹 提交于 2020-01-04 14:03:28

问题


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/



来源:https://stackoverflow.com/questions/16277783/parentcontext-index-is-not-defined-in-knockout-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!