Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Functions and AngularJS

Could anyone explain why I have access to $scope.noOfTries property in the verifyGuess function when it has been defined in the initializeGame function? Thanks in advance.

angular.module('app', []).controller('GuessTheNumberController', GuessTheNumberController);
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();
}

2 Answers

Hi Troy,

The code you have above so you've bound everything to the $scope of the controller which is correct and is behaving as expected. If you don't wish other functions to have access to this variable or other you would need to assign them a local variable but that can introduce other problems if you're expecting to have access to the said variables elsewhere in your code.

To answer your question, $scope binds all functions and properties to an instance of the GuessTheNumberController "class", once the new instance is created, all functions have unrestricted access to anything bound via $scope including properties you declare from within your HTML via ng-click for example.

One more thing, and it's more to do with good practice, instead of declaring a function to initialize your properties it's better to simply have them declared at the top of your controller so it's clear and it's to ensure no errors occur if a property isn't yet available for example.

function GuessTheNumberController($scope) {
  $scope.noOfTries = 0;
  $scope.original = Math.floor((Math.random() * 1000) + 1);
  $scope.guess = null;
  $scope.deviation = null;

  $scope.verifyGuess = function() {
    $scope.deviation = $scope.original - $scope.guess;
    $scope.noOfTries = $scope.noOfTries + 1;
  };
}

Hope that helps.

Just wondering how would I declare it locally in AngularJs?

Understand it now. Thanks.