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

前端 未结 3 1887
挽巷
挽巷 2021-02-14 06:35

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

  
相关标签:
3条回答
  • 2021-02-14 07:01

    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>    
    
    0 讨论(0)
  • 2021-02-14 07:07

    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>
    
    0 讨论(0)
  • 2021-02-14 07:25

    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>
    
    0 讨论(0)
提交回复
热议问题