我有像这样的json集合
0:{FamilyDetailId:1,姓名:Daniel,GenderId:1,Dob:/ Date(1375554600000)/,...}
1:{FamilyDetailId:3,姓名:Askar,GenderId:1,Dob:/ Date(1375554600000)/,...}
var employeeFamilyModel;
function bindModel(data) {
employeeFamilyModel = ko.mapping.fromJS(data);
ko.applyBindings(employeeFamilyModel, document.getElementById("collapseOne"));
}
function loadData (employeeGuid) {
$.ajax({
url: "/HumanResource/EmployeeProfile/EmployeeProfileFamily?employeeGuid=" + employeeGuid,
type: 'post',
contentType: 'application/json',
success: function (result) {
bindModel(result);
}
});
};
视图
<ul data-bind="foreach: employeeFamilyModel">
<li data-bind="text: Name"></li>
</ul>
我的问题是在新的UL列表中显示每个集合 例如:
<ul>
<li> Name: Daniel </li>
</ul>
<ul>
<li> Name: Askar </li>
</ul>
如何在knockoutjs中实现这一目标?
答案 0 :(得分:1)
你所拥有的所有内容都将像foreach循环一样重复。你在ko文本中所拥有的一切都只会在没有任何元素的情况下输出。
<!-- ko foreach: employeeFamilyModel -->
<ul>
<li>Name: <!--ko text: Name--><!--/ko--></li>
</ul>
<!-- /ko -->
答案 1 :(得分:0)
详细说明一下,您只需将foreach
绑定'向上移动'一个级别,以便视图模型中的每个数据元素都包含<ul>
。
<强> JS 强>:
employeeFamily = ko.observableArray([{Name: 'John Doe', Owner: 'John'},
{Name: 'Jane Doe', Owner: 'Jane'}])
ko.applyBindings(employeeFamily, document.getElementById("collapseOne"));
<强> HTML 强>:
<div id = 'collapseOne' data-bind="foreach: employeeFamily">
<label data-bind="text: 'This list belongs to ' + $data.Owner"></label>
<ul>
<li data-bind="text: $data.Name"></li>
</ul>
</div>
<强>结果强>:
This list belongs to John
John Doe
This list belongs to Jane
Jane Doe
我添加了owner属性以强调每个<ul>
绑定到不同的$data
元素。见JSFiddle example