Reputation: 65
I am not sure if I am trying to do this the best (correct?) way but I have a word game in AngularJS page where players try to guess a word. Each letter is represented by a textbox and when a player enters their guess the letter is passed to a function which checks if the letter is correct and changes the colour of the box accordingly.
So far I have the following code in my partial file:
<p>Answer: {{selectedWord}}</p>
<div>
<input type="text" name="letters[]" class="answerbox" ng-repeat="guess in guesses" id="{{'letter_'+$index}}" ng-model="guess.value" onkeyup="testResults(this)" ng-focus="this.select();" size="1" maxlength="1">
</div>
This will take the input and pass it to my function which looks like this:
function testResults(letter) {
var box_id = letter.id;
var boxparts = box_id.split("_");
var box_number = boxparts[1];
var correct_answer = selectedWord(box_number-1, 1);
var your_answer = letter.value;
your_answer = your_answer.toLowerCase();
if (your_answer == correct_answer) {
letter.style.backgroundColor = "#32e53e";
} else {letter.style.backgroundColor = "#ff6d6e"; }
var is_correct = check_all();
}
What I am unable to do is pass the value of the correct answer ($scope.selectedWord)
so that I can use it as the var correct_answer
in my function.
I have tried simply passing it in with onkeyup="testResults(this, $scope.selectedWord)"
and various alternatives but this is not working.
I would be greatful for some pointers as to how to pass this value into the function or if AngularJS offers a better way to achieve my aim.
Upvotes: 1
Views: 55
Reputation: 1218
Some quick hints:
ng-keyup
) instead of native javascript (onkeyup
) to make your live easier.ng-repeat
to "iterate" a string on a template.ng-model
to an array, so you don't have to mess with ids and stuff. If you want to highlight the inputs in green or red, just use ng-class
.I made up a little fiddle for you as an example: http://jsfiddle.net/ManuKaracho/fwp41qd2/
Upvotes: 1