Below is the JS of my angular JS Web App:
$scope.total = 50000000;
var ref = databaseService.players;
$scope.players = $firebaseArray(ref);
$scope.picked = [];
$scope.history = [];
$scope.buy = function(player) {
//remove if already added locally
var index = $scope.history.indexOf(player);
var index2 = $scope.picked.indexOf(player.id);
if(index>=0 || index2>=0 ){
$scope.history.splice(index,1);
$scope.picked.splice(index2,1);
PlayerService.removePlayerFromSelection(player);
return;
}
//max 6 allowed
if($scope.history.length>=6 || $scope.picked.length>=6){
alert('max 6 allowed');
return;
}
//to make sure moeny doesn't go below $50,000,000
if($scope.total<0){
alert('Oops! You have run out of cash');
return;
}
var selected = $scope.history.reduce(function(a,b){
a[b.position] = (a[b.position] || 0) + 1;
return a;
}, {}) || {};
if(!selected[player.position] || selected[player.position]<2 && $scope.total>0){
$scope.history.push(player);
$scope.picked.push(player.id);
PlayerService.addPlayerToSelection(player);
}else{
alert('You can add only two players per position');
}
};
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
return tot;
if (tot <0){
alert('Oops! You have run out of money')
}
}, $scope.total);
};
$scope.saveTeam = function(){
userRef.set( $scope.picked);
$location.path('/mySquad');
};
MY issue
Is there a way to alert the user when the total goes lower than 0? I tried adding an if statement into the buy() function but it did not work. I aim to have the user alerted when the total budget goes below 0.
Alternative
Another option i tired is to have the "save team" button disabled if the result of the function getTotal
results in a value less than 0. Below is the HTML code i tried but was unsuccessful with:
<button type="submit" class="btn btn-lg btn-primary btn-md " ng-disabled="history.length<6" ng-disabled="getTotal<0" ng-click="saveTeam()" > Save Team </button>
Can you try to rewrite the function as below. You need to change the place for return statement
$scope.getTotal = function(){
return $scope.history.reduce(function(tot, p){
tot = tot - p.price;
if (tot <0){
alert('Oops! You have run out of money')
}
return tot; //changed location of this line
}, $scope.total);
};