AngularJS: How to hook to the end of a digest cycle (before the browser redraws)

When you run code inside a $watch expression that forces a repaint Show archive.org snapshot (e.g. by computing an element's width, or running something like element.is(':visible')) you may end up with "page flickering" or scroll offset changes.

You can hook to the end of a digest cycle to avoid that.

The following is basically straight from the docs Show archive.org snapshot , but pretty awkward to use. Do it like this (example here is a directive):

timeout = undefined
scope.$watch ->
  clearTimeout(timeout) if timeout
  timeout = setTimeout ->
    # your code here
  true # don't trigger another digest by always returning the same value

The timeouted function will be enqueued right to the end of the current digest cycle -- you may then run code that forces a repaint without flickering and all the nasty bits.

Note that you are outside of the digest cycle, so Angular will not update any bindings.

Arne Hartherz Over 9 years ago