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

时间:2013-11-02 00:29:44

标签: angularjs random

我正在尝试使用AngularJS创建twitter bootstrap的随机跨度大小的div(.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 个答案:

答案 0 :(得分: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>

答案 1 :(得分:22)

作为已接受答案的替代方案,由于您可能会重复使用此功能,因此您可以将其转换为过滤器以方便使用:

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 :(得分:3)

即时回答以防止摘要溢出:

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>