knockout.js nested foreach access outer loop prope

2019-03-17 12:00发布

问题:

I have a nested foreach loop in knockout.js and I want to access a property from the current object in the outer loop inside the inner loop. How would I do this?

<!-- ko foreach: graduationDateRows -->                  
  <tr>
    <td class="center" data-bind="text: CalendarYear"></td>  
    <!-- ko foreach: $root.graduationDatesHeaders -->
    <td class="center" data-bind="text: /* !here! */"></td> 
    <td></td>
    <!-- /ko -->                                                                  
  </tr> 
<!-- /ko --> 

回答1:

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



回答2:

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>  


回答3:

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] }
    ]
}