knockout.js nested foreach access outer loop property

knockout.js nested foreach access outer loop property

Asked on November 28, 2018 in knockout js.
Add Comment


  • 3 Answer(s)

    Use the $parent to access 1 scope level up. So, from the inner loop Use parent to access the present item being looped on in the graduationDateRows.

    Answered on November 28, 2018.
    Add Comment

      Loop via fully unrelated arrays is possible using the $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>
    

    Answered on November 28, 2018.
    Add Comment

       To use a property in the outer loop from the present object in the inner loop use the $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>
    

       Model object of salesInfo array:

    {
      "id" : "0",
      "name" : "Human Resources",
      "years" : [
        { "year" : "2012", "values" : [250000,350000,150000,220000,450000,180000] }
      ]
    }
    
    Answered on November 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.