[英]Dynamically change elements color with Angular in ngRepeat
我正在嘗試在字符串數組的ngRepeat
中以角度為某些文本動態分配顏色。
我在弄清楚這樣做的“角度方式”時遇到了問題。 我總是可以設置一個過濾器,將適當的 HSL 配色方案踢出元素的樣式,但這將非常低效,因為它必須在每個摘要周期重新計算顏色。 ngRepeat
數組可能有幾千個項目。
如果相關,這里是文本 -> HSL 轉換代碼:
function calculateColor(value){
var saturation = [0.35, 0.5, 0.65];
var lightness = [0.25, 0.35, 0.45];
var hash = stringToHash(value);
var hsl = calculateHsl(hash, lightness, saturation);
return hsl;
}
function stringToHash(value){
var seed = 131;
var seed2 = 137;
var hash = 0;
value += 'x';
var MAX_SAFE_INT = 9007199254740991 / seed2;
var charArray = value.split('');
for(var i = 0; i < charArray.length; i++){
if(hash >= MAX_SAFE_INT){
hash == hash / seed2;
}
hash = hash * seed + charArray[i].charCodeAt(0);
}
return Math.abs(hash);
}
function calculateHsl(hash, lightness, saturation){
var H,S,L;
H = hash % 359;
hash = hash / 360;
S = saturation[hash % saturation.length];
hash = hash / saturation.length;
L = lightness[hash % lightness.length];
return [H,S,L];
}
篩選:
chatApp.filter('toHsl', function(){
return function(input){
var hsl = calculateHslColor(input);
var hslString = 'hsl('+hsl[0]+', '+hsl[1]*100+'%, '+hsl[2]*100+'%)'
return hslString;
}
});
您可以按照計划使用過濾器,但您可以通過使用 1-way binding angular 來節省性能,只需要對每個項目進行一次評估。
所以你有你的過濾器,然后你的 ng-repeat 看起來像這樣,這取決於你如何准確地綁定這些顏色:
<div ng-repeat="item in colorList">
<div>{{::('item'| toHsl)}}</div>
或者
<div ng-repeat="item in colorList | filter:toHsl">
<div> {{::item}}</div>
您可以 1 路綁定到與 1 路綁定相同的屬性,只需確保使用::
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.