我正在尝试动态设置标签的背景颜色。我是如何实现的,就是这样使用ng-style:
function getColor() {
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
}

<span ng-repeat='interest in ctrl.profile.interests'
class='label interest'
ng-style="{'background-color': ctrl.getColor()}">
{{ interest }}
</span>
&#13;
但是,每当我在getColor中使用Math时,我都会在下面得到无限的摘要循环错误。您是否可以解决此问题或动态设置背景颜色的其他解决方案?谢谢!
10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:
[
[{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#3bf02a"},"oldVal":{"background-color":"#fa8432"}},{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#c0a641"},"oldVal":{"background-color":"#bf3c51"}},{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#42fa1b"},"oldVal":{"background-color":"#a35769"}},{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#d18783"},"oldVal":{"background-color":"#f35b4"}},{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#9a0847"},"oldVal":{"background-color":"#ddd27b"}}
],
[{"msg":"{'background-color': ctrl.getColor(interest)}","newVal":{"background-color":"#cb0e35"},"oldVal":{"background-color":"#3bf02a"}}
...
]]
答案 0 :(得分:1)
您不能在视图中使用每次都返回不同值的函数。
每个摘要周期,Angular执行多个摘要,直到范围值稳定(与上一个摘要相同)。如果该范围内的值永远不会稳定,则最终会得到无限的摘要,并且在角度中止之前默认限制为10。
我建议先在控制器中构建一组随机颜色,然后在$index
中使用ng-repeat
来获取每个值:
this.randomColors = this.profile.interests.map(function(){
return ('#' + Math.floor(Math.random() * 16777215).toString(16));
});
然后在视图中:
<span ng-repeat='interest in ctrl.profile.interests'
class='label interest'
ng-style="{'background-color': ctrl.randomColors[$index]}">
{{ interest }}
</span>