Angularjs 如何根据背景颜色自动更改文本颜色?

How to automatically change text color base on background color in Angularjs?

我正在使用 ng-style 在团队列表中标记诸如团队标签之类的东西,我想让团队的名称根据填充区域背景的颜色进行更改球队的名字。问题是如果背景颜色的亮度会变暗,文本颜色会使团队名称变暗并且用户无法阅读。那我该怎么做呢?

<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};
  }
});

要在 table 中使用 ng-repeat,您必须在 tabletbody 标签中应用 ng-repeat。

更新的 plunker link 是 Working Plunker

The ng-repeat directive as the name suggests repeats the element based on the length of the collection, in this scenario it will repeat the TR element (HTML Table Row). The TBODY element of the HTML Table has been assigned ng-repeat directive in order to iterate through all the items of the Customers JSON array. For each JSON object in the Customers JSON array, a TR element (HTML Table Row) is generated and appended into the HTML Table.

这是一个根据输入颜色创建另一种颜色的函数:

 $scope.setColor = function (color) {
    colorInt = parseInt(color.slice(1),16);
    //Create other color
    otherColor = colorInt ^ 0x1FFFFFF;
    console.log(colorInt.toString(16),otherColor.toString(16));
    return {
      background: color,
      color: '#'+otherColor.toString(16).slice(1)
    };
 }

DEMO on PLNKR

最后,我找到了适合自己的解决方案。我有一个函数可以将 hex 字符串转换为 rgb 然后我使用一些逻辑来处理字体颜色。这是一些代码。

$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];
}

参考来源: