我需要在 UI 上显示来自独立 JSON 数组(lstRoles)的所有复选框,并将选定的复选框作为结果数组映射到结果 JSON 对象(tObj)中的属性角色。但我不知道如何正确地做到这一点(我刚开始学习 Knockout)。如果结果 JSON 对象已经有一些数据,如何初始化复选框。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="knockout-2.2.1.js"></script>
<script src="knockout.mapping-latest.js"></script>
</head>
<body>
<span data-bind="text: name"></span>
<ul data-bind="template: { name: 'choiceTmpl', foreach: lstRoles },click: myFunction.bind($data)"></ul>
<ul data-bind="foreach: lstRoles">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: $data.name"> </span>
<input type="checkbox" data-bind="attr: { value: $data },click: myFunction.bind($data) " />
<a href="#" data-bind="click: $parent.removePerson">Remove</a>
</li>
</ul>
<hr />
<div data-bind="text: ko.toJSON(viewModel)"></div>
<script id="choiceTmpl" type="text/html">
<li>
<input type="checkbox" data-bind="attr: { value: $data } " />
<span data-bind="text: $data.name"></span>
</li>
</script>
<script type="text/javascript">
var tObj = {"name":"John", "roles":[{id:1, name:"Role1", desc:"Desc1"},{id:2, name:"Role2", desc:"Desc2"}]};
var lstRoles=[{id:1, name:"Role1", desc:"Desc1"},{id:2, name:"Role2", desc:"Desc2"},{id:2, name:"Role3", desc:"Desc3"},{id:2, name:"Role4", desc:"Desc4"}];
var viewModel = ko.mapping.fromJS(tObj);
viewModel.alldata = lstRoles;
ko.applyBindings(viewModel);
function myFunction(data)
{
viewModel.roles.push(data);
}
</script>
</body>
</html>