带有函数调用的ng-class,用于生成随机字符串

时间:2016-11-26 21:51:40

标签: javascript angularjs

我正在为我的Angular应用程序使用Materialise Library。问题是我试图添加随机类名,以便每个标签的背景不同。

<ul class="inline-list" ng-repeat="feature in features">
 <li class="chip" ng-class="getColor()">{{feature}}</li>
</ul>

我的控制器,

function ProjectsController($scope) {
    $scope.features = ['React', 'Redux', 'Firebase'];
    const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',
     'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2', 
     'teal', 'purple', 'red darken-1'];
    $scope.getColor = () => {
      return colorClass[Math.floor(Math.random()*10)]
    }
}

浏览器抛出错误:

  

angular.js:10633错误:[$ rootScope:infdig]

请给我一些解决这个问题的线索。

1 个答案:

答案 0 :(得分:0)

好像你进入了$ scope.digest()的无限循环。

Check documentation about [$rootScope:infdig] error:

我建议像这样重写你的控制器:

function ProjectsController($scope) {

   const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',  'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2', 
 'teal', 'purple', 'red darken-1'];


  function getColor() {
     return colorClass[
             Math.floor(Math.random() * 10 )
          ]
  }

  $scope.features = [
         { technology: 'React', color: getColor() },
         { technology: 'Redux', color: getColor() },
         { technology: 'Firebase', color: getColor() },
  ];
}

另外,你应该编辑你的HTML:

<ul class="inline-list" ng-repeat="feature in features">
    <li class="chip" ng-class="feature.color">{{feature.technology}}</li>
</ul>

希望,这有帮助