javascript - AngularJs Controller 中的实时时钟功能

标签 javascript angularjs

我想显示小时、分钟和秒(实时),我在 Controller 中使用 $interval 编写了函数,但 $scope 没有更新我的 View 。

这是我的观点:

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

这是我的 Controller :

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;


    }

函数正在被调用,但 View 没有更新。

最佳答案

您的 callAtInterval 函数是在 Controller 外部声明的,因此它无权访问 $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);
});

关于javascript - AngularJs Controller 中的实时时钟功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866161/

相关文章:

javascript - 使用 ui-select 使用 Protractor 进行测试

angularjs - Angular 2 中状态参数(Angular 1 和 ui-router)的等价物是什么?

javascript - AngularJS 范围不绑定(bind) ng-repeat 中的数据

javascript - 如何使用元标记在 manifest.json 文件中添加 Urls 和 web_Urls

javascript - 可折叠的 Bootstrap 4 Accordion 无法正常工作

javascript - 如何在 Storybook + Typescript 中使用 babel-emotion-plugin?

javascript - jQuery UI 1.7.3 datepicker 与 date.js 冲突导致 "too much recursion"?

javascript - 如何在 win-list-view 中动态添加项目源

javascript - For 循环使用 Django 数据作为输入,使用 CanvasJs 创建散点图

javascript - SPA 在在线托管中不起作用