简体   繁体   中英

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

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.

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);
    };

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM