Save incremented value inside a JQuery click function

0

I have the following function.

 $('#proximo').click(function() {
         token = localStorage.getItem("userToken"); 

          page =0;

            var e = document.getElementById("idSelecionaSize");
            var size = e.options[e.selectedIndex].value;

            var search = $location.search();
            var page = search.page||page;
            var size = search.size||size;
            var sort = search.sort||'type,desc';

             page++;


            $http({
                 method: 'GET',
                 url: '/user/distritosPaginacao?page=' + page + '&size=' + size + '&sort=' + sort
            }).then(function(response) {
                $scope.distritos = response.data.content;
                $scope.number= response.data.number;
                $scope.page = response.data.totalPages;
                $scope.sort = sort;
                $scope.size= response.data.size;

            });

        });

When the user clicks on the button, the page will receive a value of 1, but in the second click the button will have a value of 1 again. I would like the value to be 2, 3, 4, ... and so on .

How to do it?

    
asked by anonymous 06.12.2017 / 19:29

1 answer

2

You are assigning the value "0" to the "page" variable, then redeclaring it (I imagine it is another variable), and in the end it is incrementing it by 1. To work, your variable needs to be declared in global scope, that is, outside this method. Once declared and started with value "0" outside of this method, it will retain the last value assigned.

Ex:

var pageIndex = 0;

$('#proximo').click(function() {
         token = localStorage.getItem("userToken"); 

            var e = document.getElementById("idSelecionaSize");
            var size = e.options[e.selectedIndex].value;

            var search = $location.search();
            var page = search.page||pageIndex;
            var size = search.size||size;
            var sort = search.sort||'type,desc';

             pageIndex++;


            $http({
                 method: 'GET',
                 url: '/user/distritosPaginacao?page=' + page + '&size=' + size + '&sort=' + sort
            }).then(function(response) {
                $scope.distritos = response.data.content;
                $scope.number= response.data.number;
                $scope.page = response.data.totalPages; // Sugiro trocar o nome desta variável para evitar ser confundida com a variável page acima
                $scope.sort = sort;
                $scope.size= response.data.size;

            });

        });
    
06.12.2017 / 19:48