从Angularjs中的每个加载更多按钮单击,从API获取10个数据

时间:2017-11-10 09:50:53

标签: javascript angularjs

我是angulajs的新手,最初我需要在点击加载更多按钮后加载前10张照片我需要再加载10张照片。

我做了一些工作:

var app = angular.module("app", []);

        app.controller("HttpGetController", function ($scope, $http) {

            $http.get('https://reqres.in/api/users?page=1&per_page=6').then(
                function (response) {                   
                    $scope.movies = response.data.data;
                    console.log($scope.movies);
            });

            $scope.loadMore = function() {
               $http.get('https://reqres.in/api/users?page=1&per_page=6').then(
                function (response) {                   
                    $scope.movies = response.data.data;
                    console.log($scope.movies);
                });
            }
        }); 

1 个答案:

答案 0 :(得分:0)

为了做到这一点。您必须跟踪最后检索的页面。您还必须将新图像添加到$scope.movies

以下是一个例子:

app.controller("HttpGetController", function ($scope, $http) {

    $scope.movies = [];
    $scope.currentPage = 1;
    $scope.itemsPerPage = 10;

    function load(page, count){
        $http.get("https://reqres.in/api/users?page=" + page + "&per_page=" + "count").then(
        function (response) { 
            Array.prototype.push.apply($scope.movies, response.data.data);
        });
    }

    load($scope.currentPage++, $scope.itemsPerPage);        

    $scope.loadMore = function() {
       load($scope.currentPage++, $scope.itemsPerPage); 
    }
}); 

正如您所看到的,每次调用load方法时,$scope.currentPage都会增加一(++)。这样,下次使用此变量作为第一个参数调用load时,将检索下一页。

在这里,我使用Array.prototype.push.apply....将HTTP响应中的项目附加到$scope.movies数组,但您可以使用任何其他方法将新项目附加到此数组。