I am prototyping a project and have a bunch of messy code. The particular part of this prototype I'm stuck on is being unable to iterate and render nested array from a JSON file using knockout. Here are some facts:
- The value of a specific key that is the issue is a list.
- Each item I'm referring to in the JSON "response" is "questions" and "answers"
- Questions are just a string
- Answers are the list
- Im breaking each item in "answer" down and insert into a radio button in html
- When knockout does its thing, each of the items is being returned all together through each iter of the radio button rendering.
- qna obj is from a function that is filtering an input by calling the json file based on "sub", removing the top node an leaving only
Here is what this case is looking like [Sorry, not enough rep points to embed images, tinypic will have to do!]
http://i64.tinypic.com/25i26xl.png
I'm brand new to using knockout js, I have read the official docs but admittedly I'm having a bit of trouble understanding it
Heres the code lines question, any suggestions would be appreciated.
//questions.json
[
{
"question": "Are you a buyer, seller or renter?",
"answers": ["Buyer", "Seller", "Renter"]
},
{
"question": "Second question",
"answers": ["yes", "no"]
}
]
1
// functions.js
function questionDisplay() {
var self = this;
self.data = ko.observableArray(qna);
}
function initQuestionDisplay() {
var qnaDataModel = new questionDisplay();
$("#questionsDisplay").modal("show");
ko.applyBindings(qnaDataModel);
}
2
<!-- test.html --!>
<div
class="modal-body"
data-bind="template: {name: 'template', data: $data}"
></div>
<script type="text/html" id="template">
<div class="diplay-frame" data-bind="foreach: {data: data, as: '_data'}">
<div class="question-box">
<h2 class="question" data-bind="text: _data['question']"/>
<p class="answers" data-bind="text: _data['answers']"/>
<div data-bind="foreach: _data['answers']">
<input type="radio" name="optionsGroup" data-bind="checked: _data['answers']" />
<span data-bind="text: _data['answers']"></span>
</div>