AngularJS: $watch and $timeout

As you might know, AngularJS has an event loop, called $digest, that checks and updates all bindings and values.

You can have a DOM element only show when a scope variable has a certain value, like this:

<div ng-show="show_div">Text in div</div>

Whenever the $digest runs, it checks if $scope.show_div is true and if it is, the div is shown. If not true, the div is hidden.

That means that in your controller you can toggle the visibility of the div by simply setting $scope.show_div = true/false. However, if you do this on mouseover an element or change the value very frequently some other way the $digest might not have had the time to finish it’s loop and the div won’t toggle as it should.

That’s where $timeout comes in. It’s a wrapper for javascript’s setTimeout with the addition that it triggers a $digest loop at the end meaning that anything you changed will be updated as it should.

So instead of $scope.show_div = true and then $scope.show_div = false you do:

$timeout(function() { $scope.show_div = true; }, 0);
//and
$timeout(function() { $scope.show_div = false; }, 0);