Search code examples
javascriptangularjsangularjs-service

Angularjs - Digest Loop/Repaint timing


having a small issue with AngularJS. See the following:

$http({method: 'GET', url: 'some/url/withJSON.json'})
      .success(function(data) 
               {
               $scope.data = data
               $animations._load('arg1')
               })

$animations is a registered service that does some stuff. Occasionally (maybe 20%) of the time the _load() method will run before the window has been painted/the digest loop completes, meaning the visualisation hasn't completed. By wrapping _load() with a setTimeout() of 10ms this has resolved it, but is there an implicit/explicit way in AngularJS to execute a callback once the digest loop has finished?


Solution

  • Without more information, I would suggest $timeout(fn) will be the best way to do this. It basically makes sure there's a break after angular completes processing for the browser to render. Roughly it is equivalent to setTimeout(fn, 0), so is what you have already suggested, but it is mockable for testing.

    There is also $scope.$evalAsync(fn) that would normally render after the current digest cycle but before the DOM renders. I tend to prefer $evalAsync as it makes things easier for me to reason about, and won't allow other non-angular happenings to occur in the meantime, but it depends which works for you.

    This answer has more detailed information about the two methods.