Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS - Variable Updating With Interval

Do angular models work with setIntervaL?

Here's an example.. if I have

<p>{{number}}</p>
<button ng-click="testFunc()">TEST</button>

For some reason it updates WITHOUT setInterval, but like this it doesn't:

scope.testFunc = function(){
    setInterval(function(){
        scope.number--;
    },1000);
};

Without setInterval the number will update every single click, but with setInverval it won't update continuously. If I click it every 5 seconds it'll jump a bunch of numbers up (so it's running in the background but the view isn't updating).

like image 949
pashOCONNOR Avatar asked Apr 23 '14 00:04

pashOCONNOR


People also ask

How to use setInterval in AngularJS?

AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing. The $interval service executes the specified function on every specified milliseconds duration.

How to cancel interval in AngularJS?

You can store the promise returned by the interval and use $interval. cancel() to that promise, which cancels the interval of that promise. To delegate the starting and stopping of the interval, you can create start() and stop() functions whenever you want to stop and start them again from a specific event.

Does setInterval repeat?

Yes, setInterval repeats until you call clearInterval with the interval to stop.


2 Answers

What's happening is that you're using setInterval which is outside of "Angular's world" so it's not updating the DOM. You have two options, one is a lot better than the other.

Use $interval. It's just like setInterval except it's part of the Angular world, so those changes will update your view (be sure to pass $interval into your directive).

scope.testFunc = function(){
    $interval(function(){
        scope.number--;
    },1000);
};

The second option is to call apply() on your current code to kick off a digest cycle, don't do that though since there is a better option.

like image 155
Tyler McGinnis Avatar answered Sep 18 '22 05:09

Tyler McGinnis


See the documentation for the interval in angular js Interval with Angular JS

You don't to use the $digest to work with interval. See the code below:

HTML

<div ng-app ng-controller="ApplicationController">   
    <pre>Number: {{ number }}</pre>
    <button ng-click="testTimer()">Test Timer</button>
</div>

JS

function ApplicationController($scope,$interval) {

    $scope.number = 99999;

    $scope.testTimer = function() {
        $interval(function() {
            $scope.number--;
        }, 100);
    };  
}

See this example in action here

like image 38
Tiago Barreto Avatar answered Sep 20 '22 05:09

Tiago Barreto