giovedì 11 giugno 2015

How set dynamically the background color in a TR element with AngularJS.

AngularJS v. 1.2.14, Bootstrap v3.3.4

In my application, I have a html page where I’d like to evidence with different background colors some rows based on “Thread affinity“ value: 1, 11, 12, …

First in my controller I have defined these functions:

function ContextsController($scope, $log, $location) {
      
var vm = this;
vm.getColor = GetColor;
function GetColor(affinity) {
if (affinity !== undefined) {
var g = 255 - (affinity * 10);
              var b = affinity * 10;

              if (g <= 0 || b > 255) {
                     return null;
              } else {
                     var color = rgbToHex(255, g, b);
                    return color;
              }                         
}
return null;
}

function componentToHex(c) {
var hex = c.toString(16);
       return hex.length === 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
       return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
})();

Then in the html page I have added this code

<tr ng-repeat="context in vm.results.contexts"
ng-style="{'background-color': vm.getColor(context.ThreadAffinity)}">
       <td>{{context.IDContext}}</td>
       <td class="text-center">{{context.ThreadAffinity}}</td>
<td>
<div class="col-md-offset-6">
<span class="glyphicon glyphicon-check" aria-hidden="true" ng-show="context.Enabled==1"></span>
                    <span class="glyphicon glyphicon-unchecked" aria-hidden="true" ng-show="context.Enabled==0"></span>
             </div>
       </td> 
</tr>

Obviously, you can change the var “g” and “b” as you prefer.


This is the result, that it works fine for me.


See you!