<div data-bind="foreach : list1">
<div data-bind="foreach : Land">
<div data-bind="text : Description">
</div>
</div>
</div>
var ViewModel = function() {
var self = this;
var _json =[
{
"Land": {
"Description": "BBA-Reman",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Zoning": {
"Description": "VA Zoning",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Insurence": {
"CompanyName": "Geico",
"Address": null,
"Phone": null,
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
},
{
"Land": {
"Description": "Star Mind",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Zoning": {
"Description": "VA Zoning",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Insurence": {
"CompanyName": "Geico",
"Address": null,
"Phone": null,
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
}
]
self.list1 = ko.observableArray(_json);
}
ko.applyBindings(new ViewModel());
为什么我的嵌套foreach不起作用?
我用这种方式绑定的那一刻然后它正在工作
<div data-bind="foreach : list1">
<div data-bind="with: Land">
<div data-bind="text : Description">
</div>
</div>
</div>
这是我的jsfiddle http://jsfiddle.net/tridip/kxumu4rs/2/
答案 0 :(得分:0)
您的JSON数据的存储方式不会支持嵌套的foreach迭代。 Land
是Object
,不是数组。
如果要迭代Land
,则需要是一个数组。例如:
http://jsfiddle.net/kxumu4rs/4/
<div data-bind="foreach : list1">
<div data-bind="foreach: Land">
<div data-bind="text : Description">
</div>
</div>
</div>
var ViewModel = function() {
var self = this;
var _json =[
{
"Land": [
{
"Description": "BBA-Reman",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
{
"Description": "BBA-Reman 2",
"ID": 2,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
],
"Zoning": {
"Description": "VA Zoning",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Insurence": {
"CompanyName": "Geico",
"Address": null,
"Phone": null,
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
},
{
"Land": [
{
"Description": "Star Mind",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
{
"Description": "Star Mind 2",
"ID": 2,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
],
"Zoning": {
"Description": "VA Zoning",
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
},
"Insurence": {
"CompanyName": "Geico",
"Address": null,
"Phone": null,
"ID": 1,
"CreateDate": null,
"CreatedBy": null,
"UpdateDate": null,
"UpdatedBy": null
}
}
]
self.list1 = ko.observableArray(_json);
}
ko.applyBindings(new ViewModel());
BBA-Reman
BBA-Reman 2
Star Mind
Star Mind 2
如果您的Land
数据不是真正的数据数组,您应该保持原样并使用已发布的with
:
<div data-bind="foreach : list1">
<div data-bind="with: Land">
<div data-bind="text : Description">
</div>
</div>
</div>