AngularJS: Scroll into View after $digest

I was using jQuery with AngularJS in one of my projects and there was a requirement to fetch some contents & I had to scroll the content to visible area upon their arrival.

The general approach to fetch content is a promise, and we can update the contents to scope in the success callback.

SomePromiseObject
.then(function( contents ) {
  $scope.contents = contents;
  $scope.loading = false;
  var value = $("#section").offset().top - $("#section").height();
  $("body").stop().animate({
    scrollTop: value
  }, 500);
});

But the issue arises while determining the offset position. We measure the offset synchronously and by that time, the $digest() hasn’t finished & hence, there is no content in the section.

In such a case, we can either defer the call using a setTimeout or $timeout and observe the $$phase.

But, what could save us from some frustration is actually – a callback function, after $digest() has finished.

Finally, I found a solution to this in git-issue comment-33020323, as mentioned in this SO answer.

And, it worked!!!

SomePromiseObject
.then(function( contents ) {
  $scope.contents = contents;
  $scope.loading = false;
  $scope.$$postDigest( function() {
    var value = $("#section").offset().top - $("#section").height();
    $("body").stop().animate({
      scrollTop: value
    }, 500);
  });
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s