如何结合离子清新和离子无限滚动?

时间:2015-05-12 02:41:48

标签: javascript angularjs ionic-framework

到目前为止我有这个并且它工作很糟糕,每次我到页面底部,它重新加载并把我扔回顶部

  <ion-content>
    <ion-refresher
      on-refresh="doRefresh()">
    </ion-refresher>
    <div ng-repeat="post in posts">
      <a ng-href="#/tabs/news/{{post.site_ID}}/{{post.ID}}">
        <h2 ng-bind-html="post.title"></h2>
        <p>{{:: post.date | date}}</p>
      </a>
    </div>
    <ion-infinite-scroll
            on-infinite="loadMore()"
            distance="1%">
     </ion-infinite-scroll>
  </ion-content>

和控制器

.controller('NewsCtrl', function($scope, $ionicLoading,
                                 $stateParams, FreshlyPressed) {

  $scope.posts = [];

  $scope.loadMore = function() {
    $scope.posts = FreshlyPressed.getBlogs($scope);
    $scope.$broadcast('scroll.infiniteScrollComplete');
  },

  $scope.doRefresh = function() {
    $scope.posts = FreshlyPressed.getBlogs($scope);
    $scope.$broadcast('scroll.refreshComplete');
  }
  $scope.doRefresh();

});

1 个答案:

答案 0 :(得分:0)

看起来问题是您在实际完成之前广播infinteScrollCompleterefreshComplete。这些似乎是异步请求,但您的响应就像它们是同步的一样。

这才是真正发生的事情:

$scope.posts = FreshlyPress.getBlogs($scope); // call goes out
$scope.$broadcast(etc); // call is still out, this is too early

// (call comes back at a variable time, $broadcast needs to occur at that time)

要处理此问题,您需要回调或承诺,具体取决于getBlogs函数的api。看起来getBlogs在内部将结果添加到$ scope或者返回一个空的数组/对象然后在结果进入时填充它,这看起来有点神奇。无论哪种方式,这都违反了单一责任原理。 getBlogs应该只返回回调/保证中的数据,让控制器决定是否使用该数据。

var limit = 10; // max results
var offset = 0; // starting index
$scope.posts = []; // add results here as they come in
$scope.loadMore = function() {
  FreshlyPressed.getBlogs(limit, offset).then(function(results) {
    $scope.posts = $scope.posts.concat(results); // add results
    offset = $scope.posts.length; // adjust offset for next query
    $scope.$broadcast('scroll.infiniteScrollComplete');
  });
}; // <-- you also had a comma here

对于刷新,您只需重置状态:

$scope.posts = []; // empty results
offset = 0; // start back at first post

现在您可以像以前一样加载更多帖子。