javascript - AngularJS 通知模型更改的 View

标签 javascript model-view-controller angularjs controller setinterval

我试图在我的 Controller 中基于 Javascript Date 对象的 View 中显示当前时间。我的 Controller 看起来像这样:

myApp.controller('DateCtrl', function($scope) {
    var date = new Date();
    $scope.minutes = date.getMinutes();
    $scope.hours = date.getHours();
    $scope.seconds = date.getSeconds();
    var updateTime = function() {
        var date2 = new Date();
        $scope.minutes = date2.getMinutes();
        $scope.hours = date2.getHours();
        $scope.seconds = date2.getSeconds();
    }
    $scope.clickUpdate = function() {
        setInterval(updateTime, 1000);
    }
});

在我看来我只是:

<div ng-controller="DateCtrl">
    <div>This is the hour: {{ hours }}</div>
    <div>This is the minute: {{ minutes }}</div>
    <div>This is the second: {{ seconds }}</div>
    <button ng-click="clickUpdate()">Click Update Here!</button>
</div>

出于某种原因,setInterval() 方法只工作一次,我无法让它按照设置每 1 秒继续运行 updateTime()。我输入了一个简单的 console.log() 语句,每 1 秒运行一次...所以我很困惑。

我还查看了 $scope.watch()$scope.digest() 但我不太确定如何使用它们/如果我应该在这种情况下使用它们。

编辑:经进一步检查,似乎 setInterval 正常工作,每 1 秒调用一次 updateTime(),但范围内的值每次通话后都不会反射(reflect)在我的 View 中。

最佳答案

这是因为您要从 Angular 世界之外 (setInterval) 更改范围。您必须$apply更改:

var updateTime = function() {
    $scope.$apply(function(){
        var date2 = new Date();
        $scope.minutes = date2.getMinutes();
        $scope.hours = date2.getHours();
        $scope.seconds = date2.getSeconds();
    });
}

或使用 Angular 感知 函数,例如 $timeout。在 this question 中查看 @asgoth 的回答创建一个 Angular 感知 setInterval() 函数。

关于javascript - AngularJS 通知模型更改的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848063/

相关文章:

model-view-controller - MVC 组件责任,需要澄清

javascript - $scope 不在函数内工作

javascript - 如何获取选定的 View ?

javascript - onsubmit 表单标签中的验证函数

asp.net-mvc - 用于操作的 MVC [HttpPost/HttpGet]

iphone - 共享 View Controller 访问模型类

angularjs - 错误 : [$resource:badcfg] Error in resource configuration. 预期响应包含数组,但获得了对象?

javascript - Angular 指令需要访问 ng-repeat 中的变量

javascript - Json 上的 Switch 语句?

javascript - JavaScript 闭包是如何被垃圾回收的