-1

I'm currently building an app where you can make neat trading cards as my introduction into AngularJS. Currently I have a set array of stats that people can choose from to build onto their character, but I'd like to make the feature more random/automated.

How do I create a function to randomly go through and assign one of the values in my array?

preview of app

Currently I am spitting out the buttons to set the stats this way:

<p ng-repeat="power in cardPowers">
      <a href="" ng-click="cardStats(power.attack,power.defense,power.cost)">
        {{power.name | uppercase}}
      </a>
</p>

And my stats array and function to set them:

$scope.cardPowers = [
{
  name: "balanced-low",
  attack: 800,
  defense: 800,
  cost: 2
},
{
  name: "balanced-medium",
  attack: 1500,
  defense: 1500,
  cost: 4
},
{
  name: "balanced-high",
  attack: 2500,
  defense: 2500,
  cost: 7
},
{
  name: "high-offense",
  attack: 2500,
  defense: 1000,
  cost: 5
},
{
  name: "base-offense",
  attack: 1500,
  defense: 1000,
  cost: 3
},
{
  name: "base-defense",
  attack: 1000,
  defense: 1500,
  cost: 3
},
{
  name: "high-offense",
  attack: 2200,
  defense: 1000,
  cost: 5
},
{
  name: "high-defense",
  attack: 1000,
  defense: 2500,
  cost: 4
},
{
  name: "high-offense-defense",
  attack: 2200,
  defense: 2500,
  cost: 6
}
];

$scope.cardStats = function(attack, defense, cost){
$scope.attack = attack;
$scope.defense = defense;
$scope.cost = cost;
};
Adrian Rodriguez
  • 175
  • 1
  • 16
  • unfortunately, it's not really clear what you are asking here. it doesn't appear that your code is broken, but there also doesn't seem to be any code here showing the feature you are describing working on. "I want to be able to..." isn't really a question. – Claies Feb 08 '17 at 15:02
  • @Claies I guess it's more of a "How do I" do this in AngularJS. If that's not an appropriate question, I can delete this. – Adrian Rodriguez Feb 08 '17 at 15:16
  • Just generate a random number between `0` and `cardPowers.length - 1` – Ankh Feb 08 '17 at 15:19
  • @Ankh thanks I will try that. – Adrian Rodriguez Feb 08 '17 at 15:20

1 Answers1

2

Use following function to get a random value from the $scope.cardPowers array.

function getRandomCardPower(){    
    return $scope.cardPowers[Math.floor(Math.random() * $scope.cardPowers.length)];
}
daan.desmedt
  • 3,752
  • 1
  • 19
  • 33