简体   繁体   中英

angular $scope variable updated but not displayed

In the below controller $scope.timer is incremented every second but in the view {{timer}} does not reflect it's content.

myapp.controller('TimeCtrl', ['$scope', function($scope){
    $scope.timer = 0;
    setInterval(function(){
        $scope.timer = $scope.timer + 1;
        console.log($scope.timer);
    },1000);
}]);

I'can solve it adding $scope.$apply(); after the timer is updated why is that ? Why is timer not updated ?

Fiddle here : http://jsfiddle.net/wvxgzx76/1/

Because setInterval is outside the $digest cycle - use Angulars $interval directive instead:

myapp.controller('TimeCtrl', ['$scope', '$interval', function($scope, $interval){
    $scope.timer = 0;
    $interval(function(){
        $scope.timer = $scope.timer + 1;
        console.log($scope.timer);
    },1000);
}]);

just wrap your code into scope apply:

var myapp = angular.module('myapp', []);
myapp.controller('TimeCtrl', ['$scope', function($scope){
    $scope.timer = 0;
    setInterval(function(){
        $scope.$apply(function () {
            $scope.timer = $scope.timer + 1;
            console.log($scope.timer);
        });
    },1000);
}]);

or use $interval instead of setInterval (i would prefer this):

var myapp = angular.module('myapp', []);
myapp.controller('TimeCtrl', ['$scope', '$interval', function($scope,$interval){
    $scope.timer = 0;
    $interval(function(){       
        $scope.timer = $scope.timer + 1;
        console.log($scope.timer);
    },1000);
}]);

http://jsfiddle.net/wvxgzx76/3/

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