AngularJS - 如何为每个ng-repeat迭代生成随机值

11

我正在尝试使用AngularJS创建随机大小的twitter bootstrap divs(.childBox)。

  <div ng-controller="HomeCtrl">
    <div class="motherBox" ng-repeat="n in news">
      <div class="childBox" class="col-md-{{boxSpan}} box">
        <a href="#" class="thumbnail">
          <img src="{{holderLink}}" height="200px" alt="100x100">
          <p class="tBlock"> {{n.title}} </p>
        </a>
      </div>
    </div>
  </div>

controller('HomeCtrl', ['$scope', '$http', function($scope,$http) {
  $http.get('news/abc.json').success(function(data) {
    $scope.news = data;
  });
  $scope.holderSize = 150;
  $scope.holderLink = 'http://placehold.it/'+$scope.holderSize+'x'+$scope.holderSize;
  $scope.boxSpan = getRandomSpan();

  function getRandomSpan(){
    return Math.floor((Math.random()*6)+1);
  };
}])

我想为每个.childBox div创建不同的整数值boxSpan,但所有.childBox都具有相同的boxSpan值。尽管每次刷新页面时,boxSpan会创建随机值。

如何为每个ng-repeat迭代生成不同的/随机值?

3个回答

25

只需要在作用域中调用getRandomSpan()函数并在模板中调用它:

$scope.getRandomSpan = function(){
  return Math.floor((Math.random()*6)+1);
}

<div ng-controller="HomeCtrl">
  <div class="motherBox" ng-repeat="n in news">
    <div class="childBox" class="col-md-{{getRandomSpan()}} box">
      <a href="#" class="thumbnail">
        <img src="{{holderLink}}" height="200px" alt="100x100">
        <p class="tBlock"> {{n.title}} </p>
      </a>  
    </div>
  </div>
</div>

14
会导致消化系统溢出,对吧? - vp_arth
2
是的,在我的情况下会导致这个问题。 - silvenon
4
为了防止内容溢出,你可以使用ng-init='rand = getRandomSpan()',在class中使用class="col-md-{{rand}} box"。该方法可以使生成的随机数字作为列宽度的一部分,从而避免内容溢出问题。 - egor.xyz

21

作为替代方案,鉴于您可能会重复使用此函数,您可以将其转换为过滤器以增加方便性:

作为一种替代方法,由于您很可能会重用这个函数,您可以将其变成一个过滤器来增加方便性:

angular.module('myApp').filter('randomize', function() {
  return function(input, scope) {
    if (input!=null && input!=undefined && input > 1) {
      return Math.floor((Math.random()*input)+1);
    }  
  }
});

然后,您可以定义最大值并在应用程序的任何地方使用它:

  <div ng-controller="HomeCtrl">
    <div class="motherBox" ng-repeat="n in news">
      <div class="childBox" class="col-md-{{6 | randomize}} box">
        <a href="#" class="thumbnail">
          <img src="{{holderLink}}" height="200px" alt="100x100">
          <p class="tBlock"> {{n.title}} </p>
        </a>
      </div>
    </div>
  </div>

2

改进已接受的答案以防止摘要溢出:

var rand = 1;
$scope.initRand = function(){
    rand = Math.floor((Math.random()*6)+1)
}

$scope.getRandomSpan = function(){
  return rand;
}

<div ng-controller="HomeCtrl">
  <div class="motherBox" ng-repeat="n in news">
    <div class="childBox" ng-init="initRand()" class="col-md-{{getRandomSpan()}} box">
      <a href="#" class="thumbnail">
        <img src="{{holderLink}}" height="200px" alt="100x100">
        <p class="tBlock"> {{n.title}} </p>
      </a>  
    </div>
  </div>
</div>    

1
不需要使用函数从作用域中获取值,否则会导致溢出。只需设置新的值:ng-init='rand = initRand()',并在类中使用:class="col-md-{{rand}} box" - egor.xyz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接