Scroll position on back

I don’t know if it will help but I threw this together and it feels close (but no cigar).

Basically this directive will capture the state name and position of scroll when you leave the page. It will then store the information in an object in an array in a service.

Then when the view is loaded again (on back for instance) the object in the array in the service is retrieved based on state name and the scroll position is applied.

.directive('keepScroll', function ($filter, $timeout, $state, $ionicScrollDelegate, $scrollPosition) {
  return function ($scope, $element, $attrs) {
    var scrollableElement = $element[0].querySelector('.scroll');
    var view = $filter('filter')($scrollPosition.views, { name: $state.current.name })[0];
    // Save scroll position on view change
    $scope.$on("$stateChangeStart", function () {

      // +++ how do I get this value? ++++
      var position = 0; //

      // Save existing view
      if (view) view.position = position;
      else {
        // Add view to collection
        $scrollPosition.views.push({
          name: $state.current.name,
          position: position
        });
      }
    });

    // Apply scroll position to view
    $timeout(function () {
      
      // +++ this doesn't exist but it would be nice if it did! +++
      if (view) $ionicScrollDelegate.scrollTo(0, view.position, false);

    }, 0);
  }
})

It’s obviously not complete, but I just thought it might be useful if anyone were to tackle this problem.

3 Likes