user4878548
user4878548

Reputation:

Update variable in every tick using setInterval() with AngularJS

I'm trying to count up a variable every x seconds in JS using setInterval() and show it in my view binding this variable the Angular way. The problem is, in the model the var is counted up but the progress is just shown as soon as I stop the Interval. How can I update the var in the view on every tick?

<span>{{number}}</span> 

and:

$scope.number = 0;
$scope.interval;

$scope.run = function(){
    $scope.interval = setInterval(function(){
        $scope.number++;
    }, 1000);
};

$scope.stop = function(){
    clearInterval($scope.interval);
}

Fiddle

Upvotes: 0

Views: 635

Answers (2)

jrath
jrath

Reputation: 990

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope, $interval) {
    $scope.number = 0;

    $scope.run = function (){
        $scope.interval = $interval(function(){ 
            $scope.number++;
        }, 1000);
    };

    $scope.stop = function() {
        $interval.cancel($scope.interval);
    };

});

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78535

You should be using Angular's implementation of setInterval called $interval.

Not only will this will ensure any code within the callback calls a digest, but it will also help you easily test your code:

$scope.run = function() {
    $scope.interval = $interval(function() {
        $scope.number++;
    }, 1000);
};
$scope.stop = function() {
    $interval.cancel($scope.interval);
};

I would also avoid attaching your interval variable to the $scope. I can't see any reason your view would need to be aware of it. A private var interval in the controller scope would suffice.

Upvotes: 3

Related Questions