javascript 如何使用angularjs选择随机元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21766233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select random element using angularjs?
提问by blue-sky
I use ng-repeat below :
我在下面使用 ng-repeat :
<div ng-repeat="quote in quotes">
{{quote.value}}
</div>
to iterate over a quotes variable :
迭代引号变量:
app.controller("MainController", function($scope){
$scope.quotes = [
{
value: "q1"
},
{
value: "q2"
},
];
});
I would like to select just one random element from this quotes variable instead of iterating over the entire array. Is there a directive in angualrjs I can use to achieve this ?
我想从这个引号变量中只选择一个随机元素,而不是遍历整个数组。我可以使用angualrjs中的指令来实现这一点吗?
回答by amankapur91
You can use this: "Getting a random value from a JavaScript arrayto get a random value.
您可以使用:“从 JavaScript 数组中获取随机值以获取随机值。
$scope.randomQuote = $scope.quotes[Math.floor(Math.random() * $scope.quotes.length)];
回答by Mouneer
We can achieve this without any of directives if they're not found:
The following method randomize an int within a range
如果找不到任何指令,我们可以在没有任何指令的情况下实现这一点:
以下方法在范围内随机化一个 int
getRandomIndex = function(){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
So in our case: min should be zero and max should be the length of the array - 1
所以在我们的例子中:min 应该为零,max 应该是数组的长度 - 1
Here is an example how to use it
这是一个如何使用它的示例
app.controller("MainController", function($scope){
$scope.getRandomIndex = function(length){
return Math.floor(Math.random() * length);
}
$scope.quotes = [
{
value: "q1"
},
{
value: "q2"
},
];
});
<div ng-controller="MainController">
<div ng-repeat="q in quotes">
<p> {{quotes[getRandomIndex(quotes.length)].value}} </p>
</div>
</div>