1

我的 randomWidth() 函数调用两次时遇到问题,即使我从元素中删除了 ng-repeat 属性,它仍然调用了两次。我似乎无法弄清楚如何解决这个问题。我猜有办法解决这个问题,或者可能是我明显遗漏的东西?

HTML:

<div id="body-wrapper" ng-app="gallery" ng-controller="mainCtrl">
<section id="sidebar">

  <h1>Gallery</h1>

</section>

<main>
  <div class="box" ng-repeat="img in imgs" ng-style="{'width': randomWidth()}">
    <div class="box-wrapper"></div>
  </div>
</main>
</div>

Javascript:

angular.module('gallery', [])
.controller('mainCtrl', function($scope){

  $scope.imgs = [
    {
      title: 'image1'
    },
    {
      title: 'image2'
    },
    {
      title: 'image3'
    },
    {
      title: 'image4'
    },
    {
      title: 'image5'
    },
    {
      title: 'image6'
    }
  ];

  $scope.randomWidth = function(){
    const widths = ['25%', '33%', '40%', '50%'];
    const max = widths.length;
    const min = 0;
    var r = Math.floor(Math.random() * (max - min)) + min;
    console.log(widths[r]);
    return widths[r];
  }
})

实时代码:http ://codepen.io/daviddiefenderfer/pen/qZpqdK

4

2 回答 2

3

请参阅此更新的代码笔 - 您需要在 JS 中调用 randomWidth,每张图片一次。你设置它的方式,它被称为第一次,它最终会修改你的元素,这会触发一个摘要循环,这会触发另一个对 randomWidth 的调用,等等,直到 Angular 停止你,因为它检测到无限循环。

http://codepen.io/lwalden/pen/KzZWXK

更改为 HTML:

<div class="box" ng-repeat="img in imgs" ng-style="{'width': img.style}">

更改为 JS:

angular.module('gallery', [])
.controller('mainCtrl', function($scope){

  $scope.randomWidth = function(){
    const widths = ['25%', '33%', '40%', '50%'];
    const max = widths.length;
    const min = 0;
    var r = Math.floor(Math.random() * (max - min)) + min;
    console.log(widths[r]);
    return widths[r];
  }

  $scope.imgs = [
    {
      title: 'image1',
      style: $scope.randomWidth()
    },
    {
      title: 'image2',
      style: $scope.randomWidth()
    },
    {
      title: 'image3',
      style: $scope.randomWidth()
    },
    {
      title: 'image4',
      style: $scope.randomWidth()
    },
    {
      title: 'image5',
      style: $scope.randomWidth()
    },
    {
      title: 'image6',
      style: $scope.randomWidth()
    }
  ];
})
于 2016-04-07T16:24:25.837 回答
1

我认为这个问题已经得到了充分的回答

我建议看看这篇文章$digest

Note: At a minimum, $digest will run twice even if your listener functions don’t change any models. As discussed above, it runs once more to make sure the models are stable and there are no changes.

于 2016-04-07T16:21:45.227 回答