Reputation: 505
I am trying to pass a JSON to knockout and display it, and I have managed to do so for the first few elements. However I am having trouble with the nested objects. What I am trying to achieve is to display the desc and value fields for each of the A1,A2,A3 / B1,B2,B3 ..
I've looked through a million examples and tried various versions, but still can't figure out how mapping works.
Many Thanks for your help.
JS:
function jsonSubsetModel (desc,value){
var self = this;
self.desc = ko.observable(desc);
self.value = ko.observable(value);
}
var myModel = function(){
var jsonUrl = '/myjson.json';
var self = this;
var mapped = {};
//Data
self.date = ko.observable();
self.time = ko.observable();
self.set1 = ko.observableArray([]);
self.set2 = ko.observableArray([]);
$.getJSON(jsonUrl,function (data) {
self.date(data.Date);
self.time(data.Time);
self.img(data.ImgURL);
mapped = ko.mapping.fromJS(data);
self.set1(mapped.SET1);
self.set2(mapped.SET2);
});
};
ko.applyBindings(new myModel());
HTML:
<!-- This works -->
<span data-bind="text: date"></span><br>
<span data-bind="text: time"></span><br>
<span data-bind="text: img"></span><br>
<!-- This doesn't -->
<p data-bind = "foreach:{data: set1, as:'subset'}">
<span data-bind="text: subset.desc"></span>
<span data-bind="text: subset.value"></span>
</p>
JSON:
{
"Date":"21/02/2013",
"Time":"13:55",
"SET1": {
"A1":{
"desc":"descA1",
"value":"30",
},
"A2":{
"desc":"descA2",
"value":"30",
},
"A3":{
"desc":"descA3",
"value":"30",
}
},
"SET2": {
"B1":{
"desc":"descA1",
"value":"30",
},
"B2":{
"desc":"descA1",
"value":"30",
},
"B3":{
"desc":"descA1",
"value":"30",
}
}
}
Upvotes: 3
Views: 1224
Reputation: 34895
The knockout.js
foreach
works with Array
. What you're providing is an object. Change your object to:
"SET1": [
{
"desc":"descA1",
"value":"30",
},
{
"desc":"descA2",
"value":"30",
},
{
"desc":"descA3",
"value":"30",
}
],
Upvotes: 3