arunmmanoharan
arunmmanoharan

Reputation: 2675

Smooth switch between colors dynamically

I am using ng-class to color a particular cell based on the value of the cell.

ng-class="{'score-cell green': value >= 70 ,                                                
'score-cell red': value <= 40,                                                
'score-cell yellow': value < 70 && value > 40}"

How can I switch between ranges something like this?

it should gradually transition from red to yellow to green.

Please advice.

Please find this plunkr here.

https://plnkr.co/edit/0EjxhxxvzWpFRF49Pzp5?p=preview

Upvotes: 0

Views: 201

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

Try using ng-style instead. Firstly you need to generate your values within the range of green and red (HSV colour space). Then turn it into Hex values and add it with background-color CSS. You can render them in a loop with ng-repeat.

Here is an example:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  // your function for converting to Hex
  function toHex(n) {
    var r = 255 - (n / 10 * 255 | 0);
    g = n / 10 * 255 | 0;
    return '#' +
      (r ? (r = r.toString(16), r.length == 2 ? r : '0' + r) : '00') +
      (g ? (g = g.toString(16), g.length == 2 ? g : '0' + g) : '00') + '00'
  }

  var c = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  $scope.colors = c.map(function(x) {
    return toHex(x)
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="c in colors track by $index" ng-style="{'background-color':c}">
    background-color: {{c}}
  </div>
</div>

Upvotes: 1

Related Questions