plamtod
plamtod

Reputation: 79

Knockout bind nested collections

I have next ViewModel with Questions collection which contains Answers collection. I tried to bind but only PoolText and elements of first collection- Questions look correct. Answers collection miss at all. Actually in the example is Javasctip model that need to be mapped. My viewmodel is like this:

function VM(){
  this.PoolText = ko.observabe();
  this.Qusetions = ko.observableArray([]);
  this.Qusetions.Answers = ko.observableArray([]);//is this correct???
} 

function Question(){
 this.ID = ko.observabe();
 this.QuestionText = ko.observabe();
 this.Answers = ko.observableArray([]);
}

function Answer(){
 this.AnswerText = ko.observabe();
 this.Points = ko.observabe();
}

var vm = {
  "ID": 1,
  "PoolText": "Pool1",
  "Questions": [{
    "ID": 2,
    "QuestionText": "Q1",
    "Answers": [{
      "ID": 3,
      "AnswerText": "A1",
      "Points": 1.00
    }, {
      "ID": 4,
      "AnswerText": "A2",
      "Points": 1.00
    }, {
      "ID": 5,
      "AnswerText": "A3",
      "Points": 1.00
    }]
  }, {
    "ID": 3,
    "QuestionText": "Q2",
    "Answers": [{
      "ID": 7,
      "AnswerText": "AA1",
      "Points": 1.00
    }, {
      "ID": 8,
      "AnswerText": "AA2",
      "Points": 1.00
    }, {
      "ID": 9,
      "AnswerText": "AA3",
      "Points": 1.00
    }]
  }, {
    "ID": 4,
    "QuestionText": "Q3",
    "Answers": []
  }]
}
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="text: PoolText"></div>
<ul data-bind="foreach: Questions">
  <li data-bind="text: QuestionText">
    <ul data-bind="foreach: Answers">
      <li data-bind="text: AnswerText"></li>
    </ul>
  </li>
</ul>

Upvotes: 1

Views: 358

Answers (1)

krivtom
krivtom

Reputation: 24916

The issue is with your HTML structure. You have a following structure for your inner items:

<li data-bind="text: QuestionText">
    <ul data-bind="foreach: Answers">
       <li data-bind="text: AnswerText"></li>
   </ul>
</li>

You use text binding on your outer tag, so everything that is inside this tag is overwritten with result from this binding. This means that inner foreach is never executed, because it is overwritten. In order to fix that you need to separate the first binding from li tag, for example like this:

<ul data-bind="foreach: Questions">
    <li>
        <span  data-bind="text: QuestionText" ></span>
        <ul data-bind="foreach: Answers">
            <li data-bind="text: AnswerText"></li>
        </ul>
    </li>
</ul>

Upvotes: 1

Related Questions