AngularJs 控制器中的实时时钟功能

Llive clock function in AngularJs controller

本文关键字:实时时钟 功能 控制器 AngularJs      更新时间:2023-09-26

我想显示小时,分钟和秒(实时),我在控制器中使用$interval编写了函数,但$scope不更新我的视图。

这是我的观点:

<div ng-controller="clockCtrl">
{{hour}}:{{min}}:{{sec}}
</div>

这是我的控制器:

angular.module('myApp').controller('clockCtrl',function($scope,$interval){

 $interval(callAtInterval, 1000);
});

    function callAtInterval(){
          console.log("this text is getting printed after each second");
          var today = new Date();
          h=today.getHours();
          var m = today.getMinutes();
          var s = today.getSeconds();
          $scope.hour=h;
          $scope.min=m;
          $scope.sec=s;

    }

函数正在接收调用,但视图未更新。

您的 callAtInterval 函数是在控制器外部声明的,因此它无法访问$scope。你应该像这样声明它:

angular.module('myApp').controller('clockCtrl',function($scope,$interval){
    function callAtInterval(){
        console.log("this text is getting printed after each second");
        var today = new Date();
        h=today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        $scope.hour=h;
        $scope.minutes=m;
        $scope.sec=s;
    }
    $interval(callAtInterval, 1000);
});