简体   繁体   中英

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:

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).

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. However as I previously stated the console.log is running and the model is being updated. 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 .

Solution 1:

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

Solution 2 :

If you can inject $timeout , then:

$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.

Try using Angulars $timeout instead of setTimeout. Otherwise you're going to need to $apply().

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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