0

I want to run a function 7 times and then put the values that it returns into 7 labels upon button click. Here's basically what i have so far

<button class="btn btn-danger btn-sm" ng-click="getRandom()">Roll</button>
<span class="label label-info">1:  </span>
<span class="label label-info">2:  </span>

$scope.getRandom = function(){  
var roll1 = Math.floor((Math.random()*(6 - 1))+1);
var roll2 = Math.floor((Math.random()*(6 - 1))+1);
var roll3 = Math.floor((Math.random()*(6 - 1))+1);
var roll4 = Math.floor((Math.random()*(6 - 1))+1);

var all = [roll1, roll2, roll3, roll4]
all.sort(function(a, b){return a-b});

var total = all[0] + all [1] + all[2];
return total;
};

I have thought about using ngRepeat to call the function 7 times or to just putting a loop in my function to return all 7 values, but i am not quite sure how to implement this or what i should do.

beefwipe
  • 3
  • 1

1 Answers1

0

You're on the right track. But instead of using the same function over and over again, try abstracting the diceRoll into its own function. That way you can reuse it in the second code block here, where you loop through, rolling the dice 7 times and pushing it into an array.

Then, use .reduce() to add all the values into the array together (see this Mozilla doc)

var all = [];
var diceRoll = function() {
 return Math.floor((Math.random()*(6 - 1))+1);
}
for (i = 0; i < 7; i++) {
  var val = diceRoll();
  all.push(val);
}

/* EDIT: Below, I don't think you wanted this, sorry, it's late! */
all.reduce(function(previous, current, index, array){
  return previous + current;
});

FINAL EDIT:

Okay, I thought this should be Angular specific since you asked--but I'm kind of thin on my knowledge in that arena, so someone else could probably tell me a more efficient or "Angular" way.

So instead, define the array of objects produced as attached to the $scope, and define the value produced by the dice roll as attached to the key "value" of a JSON object--then use the awesome JSON array sort method found here to sort the resulting array, and ng-repeat to render your array! Fiddle

var app = angular.module("myApp", []);

app.controller("myController", ["$scope", function($scope){
    $scope.all = [];
    var diceRoll = function() {
     return Math.floor((Math.random()*(6 - 1))+1);
    }
    for (i = 0; i < 7; i++) {
      var val = diceRoll();
      $scope.all.push({"value":val});
    }
    function sortResults(prop, asc) {
        $scope.all = $scope.all.sort(function(a, b) {
            if (asc) return (a[prop] > b[prop]);
            else return (b[prop] > a[prop]);
        });
    }
   sortResults('value', true);

}]);

The Markup:

<div ng-app="myApp">
    <table ng-controller="myController">
        <tr ng-repeat="a in all">
            <td>{{a.value}}</td>
        </tr>
    </table>
</div>
Community
  • 1
  • 1
bazeblackwood
  • 1,127
  • 6
  • 16