简体   繁体   English

ng-show和rootScope的AngularJS问题

[英]AngularJS issue with ng-show and rootScope

I have an app that triggers real-time events. 我有一个触发实时事件的应用程序。 And when one of those events happens, we change a model inside $rootScope with the following code: 当其中一个事件发生时,我们使用以下代码更改$ rootScope中的模型:

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

This works when the user is already in the tab and using the app. 当用户已经在选项卡中并正在使用该应用程序时,此方法将起作用。 However when the user is using another app or even in another tab, this code will update the model (I tried adding some console.logs), but it won't show the div (it doesn't remove the ng-hide class). 但是,当用户使用另一个应用程序或什至在另一个选项卡中时,此代码将更新模型(我尝试添加一些console.logs),但不会显示div(不会删除ng-hide类) 。

The only way for it to work is if I click anywhere of the app. 它起作用的唯一方法是单击应用程序的任何位置。 I did some research and saw that the issue is on the setTimeout when the tab isn't focused. 我进行了一些研究,发现当标签不突出时,问题就在setTimeout上。 However as I previously stated the console.log is running and the model is being updated. 但是,正如我之前所说的,console.log正在运行,并且模型正在更新。 So this is a weird behavior which I'm not able to figure it out. 所以这是一个奇怪的行为,我无法弄清楚。

You seem to be missing a $rootScopt.$apply or not using $timeout instead of setTimeout . 您似乎缺少$rootScopt.$apply或未使用$timeout而不是setTimeout

Solution 1: 解决方案1:

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

Solution 2 : 解决方案2

If you can inject $timeout , then: 如果可以注入$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. 选项卡具有焦点时它起作用的原因可能是其他原因可能触发了$digest循环。

Try using Angulars $timeout instead of setTimeout. 尝试使用Angulars $ timeout而不是setTimeout。 Otherwise you're going to need to $apply(). 否则,您将需要$ apply()。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM