【问题标题】:generating random colors using angular ng-repeat使用角度 ng-repeat 生成随机颜色
【发布时间】:2020-07-21 01:05:48
【问题描述】:

如何在 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>

【问题讨论】:

  • 尝试为 customerData 数组中的每个元素添加随机值(随机样式)(在 javascript 中)。
  • 您的代码中的问题在每个摘要循环中都会生成随机颜色。

标签: angularjs


【解决方案1】:

这是一个有效的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">&nbsp; {{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()
    }];

}]);

【讨论】:

    【解决方案2】:

    请尝试使用ng-initng-style

    查看:

    <div ng-repeat="customer in customerData" class="col-sm-3">
        <div class="contact-box" ng-init="customer.color = getRandomColor()" ng-style="customer.color">
        </div>
    </div>
    

    控制器:

    $scope.getRandomColor = function(){
            return {
                borderLeft: '2px solid # '+ Math.floor(Math.random() * 16777215).toString(16)
            }       
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 2014-06-01
      • 2013-01-07
      • 1970-01-01
      • 2013-04-02
      • 2015-06-15
      相关资源
      最近更新 更多