2

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 ?

blue-sky
  • 51,962
  • 152
  • 427
  • 752

2 Answers2

13

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)];
Community
  • 1
  • 1
amankapur91
  • 484
  • 4
  • 15
1

We can achieve this without any of directives if they're not found:

The following method randomize an int within a range

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

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>
Mouneer
  • 12,827
  • 2
  • 35
  • 45