Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select random element using angularjs?

I use ng-repeat below :

<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 ?

like image 801
blue-sky Avatar asked Aug 15 '26 11:08

blue-sky


1 Answers

You can use this: "Getting a random value from a JavaScript array to get a random value.

$scope.randomQuote = $scope.quotes[Math.floor(Math.random() * $scope.quotes.length)];
like image 99
amankapur91 Avatar answered Aug 17 '26 01:08

amankapur91



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!