0

I have an image I'm trying to shake when a user guesses the name of a fish wrong. I'm using a conditional ng-class="{'shake':error}". However, even when the answer is correct the image shakes. I don't believe that at anytime $scope.error is set to true. What am I missing here?

codepen

Taylor N
  • 500
  • 1
  • 3
  • 15

1 Answers1

0

I think what you want to do is return guessIsCorrect or guessIsWrong from your compare function.

$scope.compare = function(guess) {
    guess = guess.replace(/\s/g, '').toLowerCase();
    var answers = [];
    answers.push($scope.name.replace(/\s/g, '').toLowerCase());

    currentAnimal.alts.forEach(function(alt) {
        answers.push(alt.toLowerCase().replace(/\s/g, ''));
    });
    //console.log(answers);
    //console.log("Guess: " + guess + "\n");
    //console.log("Answer: " + answers + "\n");

    for (var x = 0; x <= answers.length; x++) {
        if (guess === answers[x]) {
            return guessIsCorrect();
        }
        if (x === answers.length) {
            return guessIsWrong();
        }
    }

};
  • Ah! Thank you so much! This is an obvious gap in my JavaScript knowledge. But why do I need to return either function? Shouldn't I be able to just call it? – Taylor N Jan 15 '17 at 21:10
  • I reckon there are/will be cases where both functions can fire. By using `return` you stop the function at that point and will ignore the code that comes after. You could also use `break` after guessIsCorrect or guessIsWrong is called as that would exit the for loop. – Scott Carmichael Jan 15 '17 at 21:16
  • Ah, I gotcha. Thanks for the help! – Taylor N Jan 15 '17 at 21:25