Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How to generate random value for each ng-repeat iteration

I am trying to create random span sized divs(.childBox) of twitter bootstrap using AngularJS.

  <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);
  };
}])

I want to create different integer value for boxSpan for each .childBox div but all .childBox have same boxSpan value. Although everytime i refresh page boxSpan creates random value.

How can i generate different/random value for each ng-repeat iteration?

like image 627
Fahad Billah Avatar asked Nov 02 '13 00:11

Fahad Billah


1 Answers

Just call add getRandomSpan() function to your scope and call it in your template:

$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>
like image 116
Daniel Tabuenca Avatar answered Oct 13 '22 22:10

Daniel Tabuenca