【问题标题】:angular $scope.$digest throws an error when setInterval fires itangular $scope.$digest 在 setInterval 触发时抛出错误
【发布时间】:2013-07-28 07:37:12
【问题描述】:

AngularJS v1.0.6

我正在尝试更新这个 html 标签 a

<div ng-app="ModuleName">
   <!-- html code... -->

   <h5> xhr called - <a ng-bind="requestCounter"></a> times</h5>

   <!-- html code... -->

用的是 JavaScript 代码:

angular.module('ModuleName',[])
    .controller('ControllerName', function ($scope){
        var myWorker = new Worker("./client/js/worker.js");
        myWorker.onmessage = function (e) {
            $scope.requestCounter = e.data.requestCounter;
        }
        setInterval($scope.$digest,7000);
        /*come code*/
    });

此代码引发错误 - TypeError: t is undefined angular.min.js(第 86 行)

但下面的代码可以正常工作:

var ControllerName = function ($scope) {
    var myWorker = new Worker("./client/js/worker.js");
    myWorker.onmessage = function (e) {
        $scope.requestCounter = e.data.requestCounter;
    }
    setInterval($scope.$digest,7000);
    /*come code*/
}

如何使用 angular.module 样式修复它?

**

更新

**

如果我使用 $apply 而不是 $digest 我会收到此错误

Error: this.$eval is not a function e.prototype.$apply
@http://localhost/path to angular lib/js/lib/angular.min.js

更新2

http://plnkr.co/edit/o76t49iId8ELPZuy4gei?p=preview 在这种情况下,Worker 发送消息并且 setInterval 工作正常。我下载了新的 angular.js,一切正常。 问题已结束。谢谢!

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

使用 $timeout 服务而不是 setInterval 或像

这样的包装器
function mySetInterval(callback, time){
   $timeout(function(){
         callback();
         mySetInterval(callback, time);
   }, time);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多