我的下一个ViewModel包含问题集合,其中包含答案集合。 我尝试绑定但只有PoolText和第一个集合的元素 - 问题看起来正确。答案收集错过了。 实际上在这个例子中是需要映射的Javasctip模型。我的viewmodel是这样的:
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>
&#13;
答案 0 :(得分:1)
问题在于您的HTML结构。您的内部项目具有以下结构:
<li data-bind="text: QuestionText">
<ul data-bind="foreach: Answers">
<li data-bind="text: AnswerText"></li>
</ul>
</li>
您在外部标记上使用text
绑定,因此此标记内的所有内容都会被此绑定的结果覆盖。这意味着内部foreach
永远不会被执行,因为它被覆盖了。为了解决这个问题,您需要将第一个绑定与li
标记分开,例如:
<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>