AngularJS Quizzing: Random word extraction

Web Development

So far, we’ve had a quiz with a static question and answer: a verse and then a blank to fill in the missing word. Let’s make the quiz a little less static by dynamically extracting a random word from the verse.

Unlike yesterday where all of our editing was within the HTML code, this time all of our editing will be in JavaScript, particularly the code for the controller.

The setAnswer function

I’ve created a simple function within the controller that does a few things:

  1. First, the verse is split into an array of words, using spaces as delimiters.
  2. Then we choose a random number from 0 to the length of the array. We’ll use this random number for picking a random word within the array.
  3. We then set the correct answer from the array using the random number. Before, we set this value arbitrarily, but now it’s being chosen at random.
  4. We replace the correct answer within the array with a blank placeholder.
  5. Finally, we rejoin the array using spaces, and then reset in the $scope.

What we’re left with then is a quiz that now extracts a random word from the verse for the user to guess. By the way, that’s why we needed the reference property, so the user will know which verse we’re asking about.

Why not assign setAnswer to the $scope?

Inside the controller, we’ve got two functions now: setAnswer and $scope.answeredCorrect. We need answerCorrect assigned to $scope to use it in the view where we use ng-if to display feedback.

However, we don’t need to use setAnswer from the view. We’re just updating the existing verse and correctAnswer properties. We could assign it to the $scope if we wanted to, but it’s unnecessary.