I have implemented an AngularJS score keeping game where players switch every two turns. The code works for one round, but I want to create a loop that keeps switching players. Check out my code below:
app.controller('EventController', function($scope){
$scope.score1 = 0;
$scope.score2 = 0;
$scope.playing = true;
$scope.win1 = false;
$scope.lose1 = false;
$scope.win2 = false;
$scope.lose2 = false;
//Counter
$scope.counter = 0;
$scope.totalScore = $scope.score1 + $scope.score2;
$scope.player1 = " Player 1";
$scope.player2 = " Player 2";
$scope.currentplayer = $scope.player1;
$scope.switchplayer = function(){
if ($scope.counter % 2 === 0){
if($scope.totalScore % 2 === 0){
$scope.currentplayer = $scope.player2;
} else {
$scope.currentplayer = $scope.player1;
}
}};
$scope.incrementScore1 = function() {
$scope.score1++;
$scope.counter++;
if ($scope.score1 === 11){
$scope.playing = false;
$scope.win1 = true;
$scope.lose2 = true;
console.log('Player 1 wins!');
}
};
$scope.incrementScore2 = function() {
$scope.score2++;
$scope.counter++;
if ($scope.score2 == 11){
$scope.playing = false;
$scope.win2 = true;
$scope.lose1 = true;
console.log('Player 2 wins!');
}
};
$scope.reset = function(){
$scope.score1='0';
$scope.score2='0';
$scope.playing = true;
$scope.win1 = false;
$scope.lose1 = false;
$scope.win2 = false;
$scope.lose2 = false;
};
});
<div class="container" ng-controller='EventController'>
<h1>Score Keeper</h1>
<h3>Current Serve:<span>{{currentplayer}}</span></h3>
<div class="row" ng-class="{'current': playing}">
<div class="col-md-6" ng-click='incrementScore1();switchplayer()' ng-model='score1' ng-class="{'win1': win1, 'lose1': lose1}">
<p>{{score1}}</p><br><br><br>
</div>
<div class="col-md-6" ng-model='score2' ng-click='incrementScore2();switchplayer()' ng-class="{'win2': win2, 'lose2': lose2}">
<p>{{score2}}</p><br><br><br>
</div>
</div>
<button ng-click='reset()'>Reset</button>
</div>