Reputation: 166
Given a knockout foreach binding statement
<div data-bind="foreach: Tests">
<a><span data-bind="text: testName"></span></a>
<table>
<!--table contents -->
</table>
</div>
This generates multiple div elements - each containing its own tag and table. when I click on the hyperlink, its corresponding table's visibility must toggle. I could not manipulate the contents of Tests as its from the server. How can I get this effect? Thanks in advance.
Upvotes: 1
Views: 1642
Reputation: 14995
Since Tests is an observableArray simply iterate over it in your view model and add a property to toggle visibility -
<div data-bind="foreach: Tests">
<a><span data-bind="text: testName, click: toggleIsExpanded"></span></a>
<table data-bind="visible: isExpanded">
</table>
</div>
And in your ViewModel -
function viewModel() {
self.Tests = ko.observableArray(yourData);
ko.utils.arrayForEach(self.Tests(), function (test) {
if (!test.isExpanded) {
test.isExpanded = ko.observable();
}
}
self.toggleIsExpanded = function (sender) {
sender.isExpanded(!self.isExpanded());
}
}
Now when you click on the link name it will toggle the isExpanded property which will make the table visible depending on the value of isExpanded. If you want to prevent loading everything into the DOM each time you could also use the if binding instead of the visible binding.
Upvotes: 2