AngularJS Quizzing: Let the Controller control logic

So far we’ve created a simple quizzing engine using AngularJS and somewhat separated the model (which is the data), from the view (which is what you see), and the controller (which sends data to the view and back).

We still had a bit of controlling being done inside the HTML: the answer value was still being checked within the HTML page. Let’s move that part inside the controller as well.

First, I want to set a value for the correct answer. In our case, the correct answer is ‘lender’. So, I’ll just set a property on the $scope called correctAnswer.

I can also add functions to the $scope, so I’ll create one that just returns true or false, based on whether the user answered the missing word correctly.

Finally, I’ll change the ng-if directive within the HTML page. Now instead of showing “Good Job” based on logic within the HTML page, it shows based on a function which has logic within the controller.

What’s a directive?

You may already know about the Prime Directive, but directives in AngularJS are markers that…wait for it… direct things.

Think of how signs directs traffic. Stop signs cause people to stop. Green lights prompt people to go. White lines or dashes effect which lane people drive in.

Directives are similar in Angular, in that they direct how the application will work. We’ve already put in directives in the HTML code, such as ng-app, ng-controller, etc. Those attributes are directives that tell AngularJS how to run this application.

Discover more from

Subscribe to get the latest posts to your email.