在Angular中加载下一页

时间:2015-01-06 17:10:18

标签: angularjs

我有以下Angular和HTML代码:

<script type="text/javascript">

  var application = angular.module('Application', []);

  application.service('ImageService', function ($http) {
    return {
      GetList: function () {
        return $http.get('api/images');
      },
    }
  });

  application.controller('ImageController', function ImageController($scope, ImageService) {

    ImageService.GetList()
      .success(function (data, status, headers, config) {
        $scope.images = data;
      })
      .error(function (data, status, headers, config) { });
  });

</script>

<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
  <div data-ng-repeat='image in images' class="image">
    <img src="{{image.Url}}" alt="" />
  </div>
</div>

API调用返回以下内容:

[
  {"Key":"89207","Url":"http://somedomain.com/image89207.jpg"},
  {"Key":"12321","Url":"http://somedomain.com/image12321.jpg"},
  {"Key":"23434","Url":"http://somedomain.com/image23434.jpg"}
]

当用户向下滚动到页面末尾或点击按钮说“&34;显示更多&#34;”时,我想加载下一页。

我还需要在JSON上返回NextPage值...

重点是,如果当前页面是&#34; 233&#34;那么下一页可能是&#34; 4545&#34;。

我认为API可能需要返回下一页的值和图像列表。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我同意pankajparkar。你应该处理&#39;显示更多&#39;按钮,加载更多图像并与$ scope.images连接。 ng-repeat将继续工作。这是代码示例

  <script type="text/javascript">
    var application = angular.module('Application', []);

    application.service('ImageService', function($http) {
      return {
        GetList: function(page) {
          return $http.get('api/images', {
            params: {
              page: page
            }
          });
        },
      }
    });

    application.controller('ImageController', function ImageController($scope, ImageService) {

      var page = 0;

      $scope.images = [];

      var load = function() {
        ImageService.GetList(page)
          .success(function(data, status, headers, config) {
            $scope.images = $scope.images.concat(data);
          })
          .error(function(data, status, headers, config) {});
      };

      load();

      $scope.loadMore = function() {
        page++;
        load();
      }
    });
  </script>

  <div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
    <div data-ng-repeat='image in images' class="image">
      <img src="{{image.Url}}" alt="" />
    </div>
    <div>
      <button ng-click="loadMore()">load more</button>
    </div>
  </div>