1

I would like to know what is the best way to keep checking a variable in AngularJS.

I made a simple clicker game where the user keeps gathering gold, so I need to be constantly checking the number of gold so I can perform some functions accordingly. The only thing I know is $interval, but I don't know if that's the best way since I have to write a number of seconds.

Thank you in advance.

0

1 Answer 1

5

Wherever your variable is stored (controller/directive):

$scope.goldAmount = 0; // or whatever initial value you so desire

Set a watch function

$scope.$watch('goldAmount', function(newAmount, oldAmount){
  // Do something with the amount when it changes
});

$watch allows you to 'watch' any variable within your $scope and run a call back when it changes.

Docs can be found here:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope

1
  • I'm reading it right now and trying to learn how it works. Thank you. Commented Apr 30, 2014 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.