如何使用Angularjs指令根据动态值更改文本颜色?

时间:2021-05-07 19:40:49

The objective is to create a directive which can change color of the text displayed on a list based on a dynamic value.

目标是创建一个指令,它可以根据动态值在列表中显示文本的颜色。

For example, I have an array:

例如,我有一个数组:

$scope.messages = [{user: "Eusthace", message: "Hello!", timestamp: 1431328718}];

For each user I'd like to have a different text color in the list of messages.

对于每个用户,我希望在消息列表中有不同的文本颜色。

1 个解决方案

#1


3  

To set css style (e.g. color) on an HTML element you can use ngStyle directive. To generate color based on dynamic value add functions to your controller:

要在HTML元素上设置css样式(例如颜色),可以使用ngStyle指令。要生成基于动态值的颜色,向控制器添加函数:

var hashCode = function(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
};

var intToRGB = function(i){
    var c = (i & 0x00FFFFFF)
        .toString(16)
        .toUpperCase();

    return "00000".substring(0, 6 - c.length) + c;
};

$scope.generateColor = function(string) {
    return '#' + intToRGB(hashCode(string))
};

To use it in your view:

在你的观点中使用它:

<span ng-style='{color: generateColor("dynamicValue")}'>Some Text</span>

example: JSFiddle

例如:JSFiddle

#1


3  

To set css style (e.g. color) on an HTML element you can use ngStyle directive. To generate color based on dynamic value add functions to your controller:

要在HTML元素上设置css样式(例如颜色),可以使用ngStyle指令。要生成基于动态值的颜色,向控制器添加函数:

var hashCode = function(str) {
    var hash = 0;
    for (var i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return hash;
};

var intToRGB = function(i){
    var c = (i & 0x00FFFFFF)
        .toString(16)
        .toUpperCase();

    return "00000".substring(0, 6 - c.length) + c;
};

$scope.generateColor = function(string) {
    return '#' + intToRGB(hashCode(string))
};

To use it in your view:

在你的观点中使用它:

<span ng-style='{color: generateColor("dynamicValue")}'>Some Text</span>

example: JSFiddle

例如:JSFiddle