AngularJS ng-style两次运行?

时间:2016-04-07 16:04:57

标签: javascript angularjs ng-style

我的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

2 个答案:

答案 0 :(得分: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()
    }
  ];
})

答案 1 :(得分:1)

我认为这个问题已经足够answered了。

我建议您在$digest上查看article

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.