Mr.T.K
Mr.T.K

Reputation: 2356

Get 10 data from API every Load more button click in Angularjs

I am new to angulajs, Initially I need to load first 10 photos after clicking on load more button i need to load another 10 photos.

i have done some work around:

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);
                });
            }
        }); 

Upvotes: 2

Views: 1007

Answers (1)

Titus
Titus

Reputation: 22474

In order to do this. You'll have to keep track which page was retrieved last. You also have to add the new image to the $scope.movies.

Here is an example:

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); 
    }
}); 

As you can see, every time the load method is called $scope.currentPage is increased by one (++). This way, next time load is called using this variable as the first argument, the next page is retrieved.

Here, I've used Array.prototype.push.apply.... to append the items in the HTTP response to the $scope.movies array but you could use any other method to append the new items to this array.

Upvotes: 1

Related Questions