Reputation: 113
i have something like this
View:
<ul data-bind="foreach: colaboradores">
<li>
<span data-bind="text: nome"></span>
<button
class="btn btn-success"
data-bind="click: $parent.show.bind($parent, $index)"
>
+ Informações
</button>
</li>
<!-- ko if: $parent.isDisplay -->
<li data-bind="text: idade"></li>
<li data-bind="text: city"></li>
<!-- /ko -->
</ul>
ViewModel
return {
isDisplay: ko.observable(false),
colaboradores: ko.observableArray([
{
nome: 'Daniel',
idade: 29,
city: 'Floripa'
},
{
nome: 'Iago',
idade: 22,
city: 'Floripa'
},
{
nome: 'Rafael',
idade: 26,
city: 'Jaguaruna'
}
]),
show: function ($index) {
if (!this.isDisplay()) {
this.isDisplay(true)
} else if (this.isDisplay()) {
this.isDisplay(false)
}
console.log(this.isDisplay())
console.log($index)
}
and once i click the button it renders all contents, instead i wanted to render only the content from same index that is within the foreach. All three buttons works but instead of just showing the content foreach 'colaboradores' it show all contents from all 3
Upvotes: 0
Views: 137
Reputation: 6382
That's because you only have the one isDisplay
variable.
One possible solution would be to use an array to keep track of the items you want to show.
return {
displayItems: ko.observableArray(),
colaboradores: ko.observableArray([
{
nome: 'Daniel',
idade: 29,
city: 'Floripa'
},
{
nome: 'Iago',
idade: 22,
city: 'Floripa'
},
{
nome: 'Rafael',
idade: 26,
city: 'Jaguaruna'
}
]),
toggleItem: function ($index) {
var index = this.displayItems.indexOf($index);
if (index > -1) {
this.displayItems.splice(index, 1);
} else {
this.displayItems.push($index);
}
}
}
And your HTML would look like this:
<ul data-bind="foreach: colaboradores">
<li>
<span data-bind="text: nome"></span>
<button
class="btn btn-success"
data-bind="click: $parent.toggleItem.bind($parent, $index)"
>
+ Informações
</button>
</li>
<!-- ko if: $parent.displayItems.indexOf($index) > -1 -->
<li data-bind="text: idade"></li>
<li data-bind="text: city"></li>
<!-- /ko -->
</ul>
Upvotes: 1