随机数

时间:2015-06-03 12:06:37

标签: javascript angularjs

我正在尝试使用lodash为我的图像生成随机数,每次点击图片时都应该再次渲染,我得到错误:

达到10 $ digest()迭代次数。

我该怎么做?

  <footer ng-if="ArticleService.articles.length">
    <div ng-repeat="article in ArticleService.articles" ng-click="ArticleService.setArticle(article)">
     <img
      ng-src="{{article.image || 'https://s3.amazonaws.com/reskill_prod/static/images/a' + $index + '.jpg'}}">
      <img
      ng-src="{{'https://s3.amazonaws.com/test/static/images/a' + rand() + '.png'}}">
      <div class="info">
        <p>{{article.title}}</p>
      </div>
    </div>
  </footer>

   $scope.rand = function() {
        return _.random(1, 12);
   }

2 个答案:

答案 0 :(得分:0)

您应该将随机数存储在文章上并绑定到该文章。由于rand的返回值不断变化,Angular将继续消化。

答案 1 :(得分:0)

您应该稳定模板 像这样:

  <footer ng-if="ArticleService.articles.length">
    <div ng-repeat="article in ArticleService.articles" ng-click="ArticleService.setArticle(article)">
     <img
      ng-src="{{article.image || 'https://s3.amazonaws.com/reskill_prod/static/images/a' + $index + '.jpg'}}">
      <img
      ng-src="{{'https://s3.amazonaws.com/test/static/images/a' + rand($index) + '.png'}}">
      <div class="info">
        <p>{{article.title}}</p>
      </div>
    </div>
  </footer>  


   var imgIndexes = {};
   $scope.rand = function(index) {
        return imgIndexes[index] || imgIndexes[index] = _.random(1, 12);
   }