2013-11-02 62 views
10

我正在嘗試使用AngularJS創建twitter引導程序的隨機跨度大小的div(.childBox)。AngularJS - 如何爲每個ng-repeat迭代生成隨機值

<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值。儘管每次刷新頁面框時,Span都會創建隨機值。

我如何爲每個ng-repeat迭代生成不同的/隨機值?

回答

22

就叫添加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> 
+13

會引起消化溢出,不是嗎? –

+2

是的,它導致它在我的情況。 – silvenon

+4

爲了防止消化溢出:你可以使用'ng-init ='rand = getRandomSpan()''並在class:'class =「col-md - {{rand}}框中輸入'' –

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> 
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>  
+1

不需要使用scope - 再次將消化溢出。只需設置新的val:'ng-init ='rand = initRand()''並在class:class =「col-md - {{rand}}」框中輸入「 –