Undefined when passing parameter to a JS and Angular function

Asked

Viewed 468 times

0

I have a function that receives as a parameter a value coming from HTML, however, it is coming undefined. I’m using JS and Angular.

My HTML

<div class="input-group  col-lg-3  col-md-3  col-sm-3 col-xs-12 pull-left">
   <select onchange="carregarDistritos()" id="idSelecionaSize" class="form-control" data-pager-action='pagesize'>
      <option value="5">Ver 5</option>
      <option value="15">Ver 15</option>
      <option value="20">Ver 20</option>
      <option value="25">Ver 25</option>
      <option value="50">Ver 50</option>
      <option value="100">Ver 100</option>
   </select>
</div>

My JS

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



    $scope.distritos = [];
    $scope.distrito = {}; // binding com o form

    $(document).ready(function() {
          var e = document.getElementById("idSelecionaSize");
            var size = e.options[e.selectedIndex].value;
    });



    carregarDistritos = function() {

        token = localStorage.getItem("userToken");

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


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

        }, function(response) {
            console.log(response.data);
            console.log(response.status);
        });

    };
});
  • What would that parameter be?

1 answer

2


The problem is that you are using angular, but you are recovering the value using Jquery. When $(Document). ready is fired, the value of "size" really is Undefined.

My suggestion is to use the ng-model property of angular, which is the proper way to retrieve input values from HTML, and call your ng-change method.

HTML example:

<div class="input-group  col-lg-3  col-md-3  col-sm-3 col-xs-12 pull-left">
<select ng-change="carregarDistritos()" ng-model="size" class="form-control" data-pager-action='pagesize'>
      <option value="5">Ver 5</option>
      <option value="15">Ver 15</option>
      <option value="20">Ver 20</option>
      <option value="25">Ver 25</option>
      <option value="50">Ver 50</option>
      <option value="100">Ver 100</option>    </select> </div>

EXAMPLE Controller:

carregarDistritos = function() {

        token = localStorage.getItem("userToken");

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


        //restante do seu código//

    };

You can check an example here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.