1

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.