/*
* Reading class
* containts health readings
*/
function Reading(date,weight,glucose)
{
var self = this;
self.date=ko.observable(date);
self.weight=ko.observable(weight);
self.glucose=ko.observable(glucose);
self.formattedWeight = ko.computed(function(){
var formatted = self.weight();
return formatted+" lb"
});
}
/*
* User class
* contains a user name, date, and an array or readings
*/
function User(name,date,readings) {
var self = this;
self.name = name;
self.date = date;
self.readingsArray = ko.observableArray([
new Reading(99,99)
]);
}
我知道如何使用foreach绑定来显示阅读或用户的信息。但我不知道如何在用户内部显示读数?
有没有办法使用嵌套的foreach绑定或绑定?这是我的HTML:
<h2>Users (<span data-bind="text: users().length"></span>)</h2>
<table>
<thead><tr>
<th>User name</th><th>Date</th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: users">
<tr>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: date" /></td>
<td data-bind="text: readingsArray"></td>
<td><a href="#" data-bind="click: $root.removeUser">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addUser">Add User</button>
<h2>Readings (<span data-bind="text: readings().length"></span>)</h2>
<table>
<thead><tr>
<th>Date</th><th>Weight</th><th>Glucose</th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: readings">
<tr>
<td strong data-bind="text: date"></td>
<td strong data-bind="text: formattedWeight"></td>
<td strong data-bind="text: glucose"></td>
</tr>
</tbody>
</table>
如果有人有兴趣,这是我的模特。任何帮助将不胜感激!提前谢谢!
// Overall viewmodel for this screen, along with initial state
function userHealthModel() {
var self = this;
self.inputWeight = ko.observable();
self.inputDate = ko.observable();
self.inputId = ko.observable();
self.inputGlucose = ko.observable();
// Operations
self.addUser = function(){
self.users.push(new User("",0,0,(new Reading(0,0))));
}
//adds a readings to the edittable array of readings (not yet the reading array in a user)
self.addReading = function(){
var date = self.inputDate();
var weight = self.inputWeight();
var glucose = self.inputGlucose();
if((weight&&date)||(glucose&&date))
{
self.readings.push(new Reading(date,weight,glucose));
}
else{
alert("Please complete the form!")
}
}
self.removeUser = function(userName){self.users.remove(userName)}
//editable data
self.readings = ko.observableArray([
new Reading(12,99,3),new Reading(22,33,2),
new Reading(44,55,3)
]);
self.users = ko.observableArray([
new User("George",2012),
new User("Bindu",2012)
]);
}
ko.applyBindings(new userHealthModel());
答案 0 :(得分:2)