使用setInterval时为什么不能更新时间?

时间:2015-07-19 08:03:55

标签: javascript angularjs

我正在学习AngulaJS,这是代码:

<!doctype html>
<html ng-app>
    <head>
        <script src="http://code.angularjs.org/angular-1.0.1.min.js"></script>
        <script src="script.js"></script>
    </head>

 <body>
    <div ng-controller="ClockCtrl">
      Current time is: {{ time.now }}
    </div>
  </body>

</html>

script.js:

function ClockCtrl($scope){
    var time = {};
    time.now = new Date().toString();
    $scope.time = time;
    setInterval(function(){
        $scope.time.now = new Date().toString();
        console.log(time.now);
    }, 1);
}

但我不知道为什么时间不能在html显示中更新?

1 个答案:

答案 0 :(得分:0)

您应该使用$interval指令而不是setInterval,这将在内部调用$scope.$apply()来更新绑定

function ClockCtrl($scope, $interval){      
    $interval(function(){
        $scope.time.now = new Date().toString();
    }, 1000);

    ////Or, You can use $scope.$apply() 
    //setInterval(function () {
    //    $scope.time.now = new Date().toString();
    //    $scope.$apply();
    //}, 1000);
}

DEMO