AngularJS - How to generate random value for each ng-repeat iteration
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>
As an alternative to the accepted answer, since you're likely to reuse this function, you can turn it into a filter for convenience:
angular.module('myApp').filter('randomize', function() { return function(input, scope) { if (input!=null && input!=undefined && input > 1) { return Math.floor((Math.random()*input)+1); } }});
Then, you can define the max and use it anywhere on your app:
<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>
Improvisation of the accepted answer to prevent digest overflow:
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>