GET function in ng-click

Asked

Viewed 368 times

3

I need to call a function GET through ng-click to popular a table and the function without using service works, but the function using service does not work.

Controller:

Works

$scope.carregarContratos = function() {
    $http({method: 'GET', url: config.baseUrl + '/contratos'})
    .then(function(response) {
        $scope.contratos = response.data;
    }, function(response) {
        console.log(response.data);
        console.log(response.status);
    });
};

Doesn’t work

carregarContratosPaginados = function (pageNumber) {
    ContratosAPI.getContratosPaginados(pageNumber, $scope.usersPerPage).success(function (data) {
        $scope.contratos = data;
        $scope.totalContratos = 100;
    }).error(function (data, status) {
        $scope.message = "Aconteceu um problema: " + data;
    });
};

Service:

angular.module("myapp").factory("ContratosAPI", function ($http, config) {
    var _getContratos = function () {
        return $http.get(config.baseUrl + "/contratos");
    };

    var _getContratosPaginados = function (pagina, total) {
        return $http.get(config.baseUrl + "/contratos?pagina=" + pagina + "&total=" + total);
    };

    var _saveContrato = function (contrato) {
        return $http.post(config.baseUrl + "/contratos", contrato);
    };

    return {
        getContratos: _getContratos,
        getContratosPaginados: _getContratosPaginados,
        saveContrato: _saveContrato
    };
});

ng-click:

ng-click="carregarContratosPaginados(1)"
  • 1

    Instead of using the "Success" method in your "getContractsPagging" call, use the ". then()" and see what returns in the "date" variable. If it goes wrong, post the error here too.

  • With . then() and direct loading works, but in ng-click does not. Showed no error. ng-click is like this: ng-click="carregarContratosPaginados(1)"

  • 1

    Dude, we’re not missing a $scope in the declaration of its function not? It should be $scope.carregarContratosPaginados = function (pageNumber)...

  • @Sorack Wow, that’s right, I didn’t declare the $Scope function on the controller, now it worked with ng-click as well. I don’t believe I was wrong in that haha. Taking advantage, it is better to use . then or . Success? Thank you!

  • 1

    About the then or success, depends on how you want to handle the bugs. I particularly prefer the then because it looks more like other Alps

1 answer

4


Is missing the $scope before the declaration of your method so that it is visible to the view:

$scope.carregarContratosPaginados = function (pageNumber)...

Browser other questions tagged

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