如何在ng-repeat中生成随机颜色。
我尝试了以下方式,但无法正常工作。
我收到错误消息,说:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
控制者
$scope.getRandomColor = function(){
return {
borderLeft: '2px solid # '+Math.floor((Math.random()*6)+1)
}
};
视图
<div ng-repeat="customer in customerData" class="col-sm-3">
<div class="contact-box" ng-style="getRandomColor()">
</div>
</div>
最佳答案
这是一个有效的JSFiddle:
HTML:
<div ng-app="myApp" ng-controller="dummy">
<div ng-repeat="customer in customerData" class="col-sm-3">
<div class="contact-box" ng-style="customer.color"> {{customer.name}} got: {{customer.color}}</div>
</div>
</div>
JS:
angular.module('myApp', ['ngSanitize'])
.controller('dummy', ['$scope', function ($scope) {
var getRandomColor = function () {
return {
borderLeft: '2px solid #' + Math.floor(Math.random()*16777215).toString(16)
}
};
$scope.customerData = [{
name: "Mike",
color: getRandomColor()
}, {
name: "Tom",
color: getRandomColor()
}];
}]);