Akash khan Akash khan - 1 month ago 8
AngularJS Question

ng-class add depending on group date data

I have some data in an array name with $scope.data variable.

[
{date:'02-05-2016'},
{date:'02-05-2016'},
{date:'04-05-2016'},
{date:'04-05-2016'},
{date:'05-05-2016'},
{date:'05-05-2016'},
...
...
]


I have 2 css class (color1,color2). I want to add class in ng-repeat of each date group like

02-05-2016 => color1
04-05-2016 => color2
05-05-2016 => color1
...
...


I can't figure out how it will be in ng-repeat

Answer

If you do have a mapping between dates and colors, it would be very simple.

Here is what you could do:

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
function($scope) {
  $scope.dates = [{
    date: '02-05-2016'
  }, {
    date: '02-05-2016'
  }, {
    date: '04-05-2016'
  }, {
    date: '04-05-2016'
  }, {
    date: '05-05-2016'
  }, {
    date: '05-05-2016'
  }];


}
}]);
.color1 {
  background-color: #121212;
  color: white;
}
.color2 {
  background-color: #ababab;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-repeat="dateObj in dates">
      <div ng-class-odd="'color1'" ng-class-even="'color2'">
        {{dateObj.date}}
      </div>
    </div>
  </div>
</div>

If your looking at grouping the dates with same color, here is what you could do.

Here is an example:

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.dates = [{
      date: '02-05-2016'
    }, {
      date: '02-05-2016'
    }, {
      date: '03-05-2016'
    }, {
      date: '04-05-2016'
    }, {
      date: '04-05-2016'
    }, {
      date: '05-05-2016'
    }, {
      date: '06-05-2016'
    }, {
      date: '07-05-2016'
    }, {
      date: '08-05-2016'
    }, {
      date: '09-05-2016'
    }];


    let currentColor = "color1";
    if ($scope.dates.length > 0) {
      $scope.dates[0].color = currentColor;
    }

    $scope.dates.reduce((prevObj, currentObj) => {
      if (prevObj.date !== currentObj.date) {
        currentColor = currentColor === 'color1' ? 'color2' : 'color1';
      }
      currentObj.color = currentColor;
      return currentObj;
    });

  }
]);
.color1 {
  background-color: #121212;
  color: white;
}
.color2 {
  background-color: #ababab;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-repeat="dateObj in dates track by $index">
      <div ng-class="dateObj.color">
        {{dateObj.date}}
      </div>
    </div>

  </div>
</div>