I'm using ng-style
to mark something like the label of a team in teams list, and i want to make the name of team will be change base on its color which filled in background of cover area of the team's name. The problem that is if the brightness of background color is gonna be dark, the text color will make the team's name gonna be dim and user unable to read. So how can i do that?
<tr ng-repeat="team in teams">
<td>{{ team.id }}</td>
<td><span ng-style="setColor(team.color)" style="color: #888;">{{ team.name }}</span></td>
</tr>
app.controller('teamController', function($scope){
$scope.teams = [
{
id: '1',
name: 'Driver',
color: '#b9774d'
},
{
id: '2',
name: 'Finance',
color: '#FEFFB3'
}
];
$scope.setColor = function (color){
return {background: color};
}
});
Finally, i found for my own solution. I have a function which will convert the hex
string to rgb
then i use some logic to handle the font color. Here is some code.
$scope.setColor = function (color) {
var rbg = hex2rgb(color);
var o = Math.round(((parseInt(rbg[0]) * 299) +
(parseInt(rbg[1]) * 587) +
(parseInt(rbg[2]) * 114)) / 1000);
var force = (o > 200) ? '#888' : 'white';
return {background: color, color: force};
};
function hex2rgb( colour ) {
var r,g,b;
if ( colour.charAt(0) === '#' ) {
colour = colour.substr(1);
}
if ( colour.length === 3 ) {
colour = colour.substr(0,1) + colour.substr(0,1) + colour.substr(1,2) + colour.substr(1,2) + colour.substr(2,3) + colour.substr(2,3);
}
r = colour.charAt(0) + '' + colour.charAt(1);
g = colour.charAt(2) + '' + colour.charAt(3);
b = colour.charAt(4) + '' + colour.charAt(5);
r = parseInt( r,16 );
g = parseInt( g,16 );
b = parseInt( b ,16);
return [r, g, b];
}
Reference source: