2

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.

9
  • Please be more specific about color system and determining criteria... can be done so many different ways Commented Sep 26, 2015 at 3:56
  • The criteria is different user, different color Commented Sep 26, 2015 at 4:07
  • 500 users 500 colors? Assigned once per user or different color depending on the time of day they log in...come on...do a little bit more thinking Commented Sep 26, 2015 at 4:08
  • Exactly, 500 users, 500 colors, its what my client wants. I understand your concern, but is what I need to do... And thank you for your time. :-( Commented Sep 26, 2015 at 4:09
  • 1
    Hope it will be helpful for you: jsfiddle Commented Sep 26, 2015 at 10:09

1 Answer 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:

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Eusthace be careful by using such behavior, because you can meet situation when generated color will be similar or the same with background color.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.