I'm trying to find a way to apply a css class to the first record when binding an array using foreach in Knockout. My end result needs to look like this.
var viewModel = function() {
this.records = ["A", "B", "C"]
};
with a template that results in:
<tbody>
<tr>
<td class="special-class">A</a>
<td>A</a>
<td>A</a>
</tr>
</tbody>
The only option I can come up with is doing an afterRender and finding the first child and doing the addClass myself using jQuery. Are there any better options?
UPDATE:
I realize I made a mistake in my example in that my actual data is a bit more complicated so here is what my templates look like:
<div id="calendar">
<table>
<thead>
<tr data-bind="template: {name: 'calendarHeadTemplate', foreach: days}"></tr>
</thead>
<tbody data-bind="template: {name: 'calendarTemplate', foreach: timeSlots}"></tbody>
</table>
</div>
<script id="calendarHeadTemplate" type="text/html">
<th data-bind="text: $data"></th>
</script>
<script id="calendarTemplate" type="text/html">
<tr data-bind="foreach: $data">
<td data-bind="text: $data"></td>
</tr>
</script>
And here is what the data looks like:
var viewModel = function() {
this.days = ["Thu 15", "Fri 16"];
this.timeslots = [["1","2"],["3","4"]];
};
In your tempalte, try:
<td data-bind="css: {'special-class' : $root.records[0] === $data}"></td>
The previous solution doesn't work in my case. I used $index == 0 to see if it's the first child, I wander how to get the last child
<td data-bind="css: {'special-class' : $index() == 0}"></td>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With