在ng-repeat中将项添加到数组后保持滚动位置

时间:2015-02-04 20:11:33

标签: javascript angularjs ionic

当用户滚动到顶部较旧的消息通过离子刷新加载时,通过ng-repeat显示消息列表。期望的行为是将旧消息添加到当前消息之上,并保留当前消息的滚动位置。

HTML

<ion-content id="messageScroller" delegate-handle="userMessageScroll">

  <ion-refresher pulling-icon="ion-ios-arrow-thin-down" refreshing-text="loading messages" on-refresh="moreMessages()">
  </ion-refresher>

  <div ng-repeat="message in convo.messages">
    {{message.text}}
  </div>
</ion-content>

JS

$scope.moreMessages = function() {
  $scope.convo.messages = olderMessages().concat($scope.convo.messages)
}

问题是当调用更多消息时,离子内容会滚动到顶部(保持在顶部?)。

如何设置滚动位置,以便加载旧邮件只是通过向上滚动来访问旧邮件?就像在iMessage或其他聊天应用程序中一样吗?

2 个答案:

答案 0 :(得分:2)

调查$ionicScrollDelegate。您可以设置并获取滚动位置

答案 1 :(得分:0)

我需要在我的应用中执行相同的操作并制定指令,只需将<load-more-at-top>指令放在<ion-list>中的<ion-content>

之前

这是一个有效的plunker

myApp.directive('loadMoreAtTop', function($timeout) {
  return {
    restrict: 'E',
    scope: { onScroll: '&onScroll' },
    require: '^$ionicScroll',
    template: function() {
        return '<ion-refresher pulling-text="More..." on-refresh="growBounds()"></ion-refresher>';
    },
    link: function($scope, $element, attrs, scrollCtrl) {
      var scroller = scrollCtrl.$element[0];
      var lastHeight, 
          loading = false;
      $scope.growBounds = function growBounds() {
          loading = true;
          lastHeight = scroller.scrollHeight;
          console.log('lastHeight', lastHeight);
          $scope.onScroll();
      }

      function resetScrollPosition() {
          var height = scroller.scrollHeight;
          var difference = height - lastHeight;
          console.log('difference', difference, 'height', height, 'lastHeight', lastHeight);
          // reset the scroll based on previous height
          scrollCtrl.scrollTo(scrollCtrl.getScrollPosition().left, difference, true);
      }

      function finishGrowBounds() {
        if(loading) {
          $timeout(function() {
              loading = false;
              resetScrollPosition();
              $scope.$broadcast('scroll.refreshComplete');
          }, 0);
        }
      }

      $scope.$parent.$on('scroll.loaded', finishGrowBounds)
    }
  };
});