Miguel February 2016

Add class in angular on ng-repeat when item is contained on array

On an Angular controller I have an array of events:

vm.events = [
  { date: "18-02-2016", name: "event A" },
  { date: "18-02-2016", name: "event C" },
  { date: "24-02-2016", name: "event D" }
];

And I have an array of all days in current month:

var days = [
  { date: "01-02-2016" },
  { date: "02-02-2016" },
  { date: "03-02-2016" }
  ...
];

On my angular view I have the following:

<span
  class="day"
  ng-class="{ 'today': isToday(day) }"
  ng-repeat="day in vm.days">{{getDay(day)}}</span>

How can I add a class to the span when a day has events, e.g., when the day has at least one record in vm.events?

Answers


Dalorzo February 2016

You can use ngClass, the way to do is by adding your condition like:

ng-class="{true:'today'}[isToday(day)]"


Sunil D. February 2016

The first thought might be to write some function that takes a date and then and it determines if that dates has any events by iterating over the events array.

That will result in a lot of unnecessary iteration on each digest cycle. Instead, you can manipulate the data before it's rendered in the ng-repeat. Modify the data such that each day has an array of events. Now you can just check if that day's events array contains any events.

Ideally, I would try and change this on the server, so that data came down in such a fashion. But there's no reason the client can't do it. Here's a simple implementation:

angular.forEach(vm.days, function(day) {
  // this modifies the day objects in vm.days, if you didn't want to
  // do that you could copy them and produce a separate array of days
  // with events...
  day.events = vm.findEventsFor(day))
});

vm.findEventsFor(day) {
  var events = [];
  angular.forEach(vm.events, function(event) {
    if (event.date === day.date) {
      events.push(event);
    }
  }
  return events;
}

Your ng-class might look like this:

ng-class="{today: isToday(day), hasEvents: day.events.length > 0}"


Ali Adravi February 2016

Here is your solution:

<div ng-repeat="day in days">
  <span ng-class="{true:'today', false: 'day' } [isToday(day.date)]">
     {{day.date}} : {{isToday(day.date)}}
  </span>
</div>

Check the working plunker

Post Status

Asked in February 2016
Viewed 2,414 times
Voted 10
Answered 3 times

Search




Leave an answer