AngularJS ng-show 和 rootScope 的问题

AngularJS issue with ng-show and rootScope

我有一个触发实时事件的应用程序。当其中一个事件发生时,我们使用以下代码更改 $rootScope 中的模型:

setTimeout(function(){$rootScope.controlsVisible = true}, 1500);

当用户已经在选项卡中并使用应用程序时,这会起作用。然而,当用户使用另一个应用程序甚至在另一个选项卡中时,此代码将更新模型(我尝试添加一些 console.logs),但它不会显示 div(它不会删除ng-隐藏 class).

它运行的唯一方法是单击应用程序的任意位置。我做了一些研究,发现问题出在标签未聚焦时的 setTimeout 上。 然而,正如我之前所说,console.log 是 运行 并且模型正在更新。所以这是一种我无法理解的奇怪行为。

您似乎缺少 $rootScopt.$apply 或未使用 $timeout 而不是 setTimeout

解决方案一:

setTimeout(function(){  
  $rootScope.$apply(function () {
       $rootScope.controlsVisible = true;  
  }
}, 1500);

解决方案 2

如果可以注入$timeout,那么:

$timeout(function() { $rootScope.controlsVisible = true; }, 1500);

The reason it is working when the tab has focus could be that something else which might be triggering the $digest loop.

尝试使用 Angulars $timeout 而不是 setTimeout。否则你将需要 $apply().

https://coderwall.com/p/udpmtq/angularjs-use-timeout-not-settimeout