AngularJS ng风格的跑步两次

AngularJS ng-style running twice?

本文关键字:两次 ng 风格 AngularJS      更新时间:2024-03-17

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

查看此更新的代码笔-您需要在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()
    }
  ];
})

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

我建议看一下这篇关于$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.