Index in ng-class doesn't work properly

212 Views Asked by At

I have a problem with this code:

<div>
                <table class="list" border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr class="headerRow">
                            <th>Action&nbsp;</th>
                            <th>Busy&nbsp;</th>
                            <th>Subject&nbsp;</th>
                            <th ng-repeat="hour in hours">{{hour | number:2}}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="item in items">
                            <td>{{item.name}}</td>
                            <td>{{item.activityDate | date:'dd/MM/yyyy'}}</td>
                            <td>{{item.subject}}</td>
                            <td ng-repeat="hour in hours"
                                ng-class="{BusyCell: hours[$index] >= item.startDateTime && hours[$index] <= item.endDateTime}"></td>
                        </tr>
                    </tbody>
                </table>
            </div>

In ng-class I would color every cell that is in the array startDateTime and endDateTime, but it works only for the first row that has only a value in those arrays, for the second that has two doesn't work. Do you have any suggestion? Thanks in advance!

2

There are 2 best solutions below

1
On

Here is a basic plnkr

However, it's showing that you don't need to use $index. You already have access to the hour at the index you're on, because of the ng-repeat.

<td ng-repeat="hour in hours" ng-class="{BusyCell: hour >= item.startDateTime && hour <= item.endDateTime}">
</td>
1
On

I think you are forgetting the use of "track by $index" inside your ng-repeat.

Example:

<div ng-repeat="n in [42, 42, 43, 43] track by $index">

Check out the docs. https://docs.angularjs.org/api/ng/directive/ngRepeat