angular $ scope变量已更新但未显示

时间:2014-10-30 16:17:13

标签: javascript angularjs

在下面的控制器中,$ scope.timer每秒递增一次,但在视图{{timer}}中没有反映它的内容。

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

我可以解决它在更新计时器后添加$scope.$apply();的原因是什么?为什么计时器没有更新?

在这里小提琴:http://jsfiddle.net/wvxgzx76/1/

2 个答案:

答案 0 :(得分:1)

因为setInterval超出$digest周期 - 请改用Angularjs $interval指令:

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

答案 1 :(得分:1)

将代码包装到范围适用:

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

或使用$ interval而不是setInterval(我更喜欢这个):

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/