1

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.

1
  • try ng-keyup instead of onkeyup="testResults(this)" Commented Jul 2, 2016 at 7:46

2 Answers 2

1

Some quick hints:

  • Always use angular directives (ng-keyup) instead of native javascript (onkeyup) to make your live easier.
  • You can use ng-repeat to "iterate" a string on a template.
  • Set your 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/

Sign up to request clarification or add additional context in comments.

1 Comment

This works as is but could you please tell me how I might use this if my HTML file is a partial ? My controller is called Gamecontrol but if I simply change the div line to ng-controller="Gamecontrol as vm" I get a function undefined error. If I leave this out I do not get an error but no text boxes are displayed.
0

Angular way of keyup ng-keyup="testResults(guess.value)"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.