knockout.js nested foreach access outer loop property

南楼画角 提交于 2019-12-03 04:39:39

You can use $parent to access one scope level up. So, from your inner loop you can use parent to access the current item being looped on in your graduationDateRows

Stas Slabko

You can even loop through completely unrelated arrays using $parent and as aliasing in foreach binding.

Consider the following example:

var VM = function(){
    this.rows = ['one','two','three'];
    this.cols = [1,2,3,4,5];
}
ko.applyBindings(new VM());
<table border="1">
    <tr>
        <th></th>
        <!-- ko foreach: cols -->
        <th data-bind="text: $data"></th>
        <!-- /ko -->
    </tr>
    <!-- ko foreach: {data: rows, as: 'row'} -->
    <tr>
        <th data-bind="text:row"></th>
        <!-- ko foreach: {data: $parent.cols, as: 'col'} -->
        <td data-bind="text:row + '/' + col"></td>
        <!-- /ko -->
    </tr>
    <!-- /ko -->  
</table>  
Himeshi

To access a property in the outer loop from the current object in the inner loop you can use $parent.property_name.

E.g.:

<ul id="salesInfo" data-bind="foreach : salesInfo ">
    <li class="department">
        <a href="#" data-bind="text: name" />
        <ul id="salesDept" data-bind="foreach: years">
            <li class="years">
                <a href="#" data-bind="text: year, click:function(data, event) { $root.yearClicked(year,$parent.name,data) }" />
            </li>
        </ul>
    </li>
</ul>

Sample object of salesInfo array:

{
    "id" : "0",
    "name" : "Human Resources",
    "years" : [
        { "year" : "2012", "values" : [250000,350000,150000,220000,450000,180000] }
    ]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!