The controller manages the model and the view. It is always designed with the view in mind and it is the view's behavior that drives controller functionality. In AngularJS, the controller is a JavaScript class (a constructor function) that hosts the model and exposes some behavior that the view binds to. How it binds to the view will be clear when we discuss the view implementation.
Let's start working on the controller implementation. While defining our model, we have already detailed the functional aspect of the application and we do have a fair idea about how the view should behave. Keeping that in mind, this is how the app controller looks:
function GuessTheNumberController($scope) { $scope.verifyGuess = function () { $scope.deviation = $scope.original - $scope.guess; $scope.noOfTries = $scope.noOfTries + 1; } $scope.initializeGame = function () { $scope.noOfTries = 0; $scope.original = Math.floor((Math.random() * 1000) + 1); $scope.guess = null; $scope.deviation = null; } $scope.initializeGame(); }
Add this controller script to the file created earlier after the Angular script declaration inside its own script block.
The GuessTheNumberController
function sets up some model properties that we described in the The app model section and exposes two methods: verifyGuess
and intializeGame
.
The verifyGuess
function verifies whether the guess matches the original value and updates model properties deviation
and noOfTries
accordingly. The initializeGame
function is used to initialize the model properties before the start of the game, and during the game whenever the user clicks on the Restart button.
The last statement in the preceding controller calls initializeGame
to set up the game for the first time.
The overall controller implementation is self-explanatory but the only oddity seems to be the $scope
object. This $scope
object has been passed as a parameter to the controller function and all functions and properties are attached to $scope
. To understand the role of the $scope
object and how things tie together, we need to start implementing the view.
However, we are still not done with the controller yet. We will revisit the controller once we get the app running and learn a bit more about them.