Angular 的网络工作者未更新视图

Web worker with Angular not updating view

我有两个文件 1) app.js 2) worker.js

我尝试更新 $scope.time 但它没有显示在视图中。这是我第一次接触网络工作者。

app.js

angular.module('App', [])

.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {

    $scope.time = 100;

    var worker = new Worker('worker.js');

    worker.onmessage = function(e) {

        $scope.time = e.data.time;

      };

    worker.postMessage($scope.time);

}]);

worker.js

 self.onmessage = function(e) {
 var time = e.data;

 var timer = setInterval(toDo,1000);

 function toDo(){

   time = time-1;
   postMessage({
     time:time
   });

  }

}

worker.onmessage 被触发时,它将在 Angular 摘要周期之外。因此,即使您更新了模型,Angular 也不知道它需要更新视图。为了让您通知 Angular 必须进行新的摘要循环,您需要调用 $scope.$apply()

worker.onmessage = function(e) {
   $scope.$apply(function(){ 
      //do model changes here
      $scope.time = e.data.time;
   });        
};

除了将匿名函数传递给 $scope.$apply,您还可以只进行更改,然后不带任何参数调用 $scope.$apply()。但我相信最好将匿名函数与 $apply 一起使用,因为它在幕后工作就像将它包装在 try...catch.

中一样
$scope.time = e.data.time;
$scope.$apply();