Don’t make me ngRepeat myself

Web Development

Today we’re going to look at another directive from AngularJS: ngRepeat.

Here’s what we’ve got so far in our quizzing fiddle:

Currently, the way the quiz works is that there’s a block of text, some underscores indicating where the answer needs to go, and then a text input field underneath. It works, but I want the input field inside the verse, so it feels like you’re completing the verse.

To do that, I’m going to use ngRepeat.

Here’s the updated fiddle:

Just like before, I’ll break the verse string into an array and pick a random number for choosing which word to leave blank for input. However, instead of just joining the array back together, I’m going to create a new array, verseObjects, that will hold objects instead of just strings. These objects will have two properties: text (the string of the word) and blankForInput (a boolean the flags whether the word or input field should be displayed). To build the new array, I’ll loop through the verseArray and then push the objects to verseObjects. Once verseObjects is ready, I can then replace the $scope.verse string with this array of objects.

After building the array, I can now use ngRepeat to iterate through all the objects inside verseObjects. I then can use ngIf to decide whether to display text or an input field.

One thing to note, there are probably hundreds of different ways to do something like this. I’m only doing it this way to show a bit how ngRepeat works.

Now, by changing the way we process the verse, I discovered I’m not able to use the same method of checking the answer. So instead of using a function to check the answer, I’m using another directive, ngPattern, which I plan to explain in more detail later this week.