javascript - How to change text color based on a dynamic value using Angularjs directives? -


the objective create directive can change color of text displayed on list based on dynamic value.

for example, have array:

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

for each user i'd have different text color in list of messages.

to set css style (e.g. color) on html element can use ngstyle directive. generate color based on dynamic value add functions controller:

var hashcode = function(str) {     var hash = 0;     (var = 0; < 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 in view:

<span ng-style='{color: generatecolor("dynamicvalue")}'>some text</span> 

example: jsfiddle


Comments