如何在knockout中从外部foreach循环访问索引变量

时间:2016-02-23 16:21:20

标签: knockout.js foreach

我能够访问外部foreach循环索引直到2个级别,但在第三级,它无法正常工作。以下代码,如何获取最内层foreach循环中第一个foreach循环的索引:

<!-- ko foreach: Clauses-->
<!-- ko foreach: ClauseRepeatingSections -->
<!-- ko foreach: RepeatingSectionElements -->
    How to get Clauses item index here?

2 个答案:

答案 0 :(得分:1)

基本上你要去2级了

$parentContext.$parentContext.$index()

请参阅以下示例 https://jsfiddle.net/wgsdddtj/

&#13;
&#13;
var viewModel = function () {
	var self = this;
  
  var Product = function (name, products) {
  	var pSelf = this;
    pSelf.name = ko.observable(name);
    pSelf.items = ko.observableArray(products);
  };
  
  self.products = ko.observableArray([
  	new Product("product1", [
    	new Product("product1a", [
      	new Product("product1aI", []),
        new Product("product1aII", [])
      ]),
      new Product("product1b", [
      	new Product("product1bI", []),
        new Product("product1bII", [])
      ])
    	]),
    new Product("product2", [
    	new Product("product2a", [
      	new Product("product2aI", [])
      ]),
      new Product("product2b", [
      	new Product("product2bI", [])
      ])
    	])
  ]);
};

ko.applyBindings(new viewModel());
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<ul data-bind="foreach: { data: products, as: 'level1' }">
  <li>
    <span data-bind="text: name"></span>
    <ul data-bind="foreach: { data: items, as: 'level2' }">
      <li>
        <span data-bind="text: name"></span>
        <ul data-bind="foreach: { data: items, as: 'level3' }">
          <li>
            <span data-bind="text: name"></span> - lvl1: 
            <span data-bind="text: $parentContext.$parentContext.$index()"></span> - lvl2:
            <span data-bind="text: $parentContext.$index()"></span> - lvl3:
            <span data-bind="text: $index()"></span>
          </li>
        </ul>
      </li>
    </ul>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

为了使代码更全面,我建议使用这样的foreach:

<!-- ko foreach: { data: Clauses, as: 'clause' } -->
    <!-- ko foreach: { data: clause.ClauseRepeatingSections, as: 'repeatingSection' } -->
        <!-- ko foreach: { data: repeatingSection.RepeatingSectionElements, as: 'element' } -->
            // each of the current level is now stored in the variable you called it in 'as' parameter. To access the current clause:
            clause.anyPropertyOrFunction
        <!-- /ko -->
    <!-- /ko -->
<!-- /ko -->