Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying class to first value in array when template foreach binding with Knockout

Tags:

knockout.js

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"]];
};
like image 305
Shane Courtrille Avatar asked Mar 16 '12 15:03

Shane Courtrille


2 Answers

In your tempalte, try:

<td data-bind="css: {'special-class' : $root.records[0] === $data}"></td>
like image 193
Mark Robinson Avatar answered Oct 03 '22 08:10

Mark Robinson


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>
like image 38
Menelaos Vergis Avatar answered Oct 03 '22 08:10

Menelaos Vergis