I am trying to make a basic function that adds 1 to the variable 'wood' every second.
In javascript, a simple
setInterval(function(){
wood++;
}, 1000);
would do the trick.
In Angular, I've been shown
app.controller('RandomCtrl', function($interval){
this.wood = 0;
$interval(function(){
this.wood++;
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('RandomCtrl', function($interval){
this.wood = 0;
$interval(function(){
this.wood++;
document.getElementById('p').innerHTML = this.wood;
}, 1000);
});
</script>
<div ng-app='app' ng-controller='RandomCtrl as rand'>
Wood: {{ rand.wood }}
<br><br>Wood's value straight from the $interval:<p id='p'></p>
So, the interval is fine, but the variable is undefined inside it, which is the whole point of me using this interval.
<br><br>Also, I want this.wood to hold the value, nothing else.
</div>
However, the code above for some reason doesn't work.
It treats this.wood+1 as 'NaN' and this.wood as 'undefined'
Here's the snippet: