本文介绍了AngularJS-如何为每个ng-repeat迭代生成随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用AngularJS创建Twitter引导程序的随机跨度大小的divs.childBox.
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);
};
}])
我想为每个.childBox div的boxSpan创建不同的整数值,但是所有.childBox都具有相同的boxSpan值.尽管每次我刷新页面boxSpan都会创建随机值.
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.
如何为每次ng-repeat迭代生成不同/随机值?
How can i generate different/random value for each ng-repeat iteration?
推荐答案
只需调用将getRandomSpan()
函数添加到您的作用域并在模板中调用它即可:
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>
这篇关于AngularJS-如何为每个ng-repeat迭代生成随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!