Pass variable from a controller to a service

0

angular.module('myApp').controller('paginasCtrl', function($scope, CarregaItens) {

  function carregaPaginas () {
      CarregaItens.getPaginas()
      .success(function (data) {
        $scope.paginas = data;
      })
  };

  carregaPaginas();
 
});


.service('CarregaItens', function ($http) {

  getInfoPage = function () {
    return $http.get("http://www.meusite.com.br/api/paginas.php?id=4");
  };

  return {
    getPaginas: getInfoPage
  }

});
<div class="col col-50 shop-product-narrow-card" ng-repeat="item in paginas" ui-sref="app.detalhes({id: item.id})">
	<div class="list card">
	  <div class="item item-image">
	    <pre-img ratio="_1_1" helper-class="main-image">
	      <img ng-src="http://www.meusite.com.br/img/paginas/{{item.imagem}}"spinner-on-load></pre-img></div><divclass="item item-body">
	    <h2 class="card-title">{{item.titulo}}</h2>
	  </div>
	</div>
</div>

Personally, I have this controller and this service that interact perfectly well, but what I need is that the item.id being listed in the view is sent to my service, replacing the static "4" of the API url. I already tried to use $ routeparams but by injecting it into the controller it stops working.

My reasoning would be for something like

return $http.get("http://www.meusite.com.br/api/paginas.php?id=" + id);

But it does not work (logical). Any ideas?

    
asked by anonymous 26.02.2016 / 20:11

2 answers

2

You should import $stateParams and use $stateParams.id . Also in $http.get() you should use the config object to be as shown below. This will work

return $http.get("http://www.meusite.com.br/api/paginas.php", { 
  params: {
    tipo: 'pagina', 
    user: '4', 
    id: $stateParams.id
  }
});

I hope it works

    
26.02.2016 / 20:46
0

If you are using ngRoute, you can inject the "$ routeParams" into the controller (I believe it is not possible to use "$ routeParams" in the service, so this is giving error) and pass the Id as parameter in the service. Something like this:

angular.module('myApp').controller('paginasCtrl', function($scope, $routeParams, CarregaItens) {

  function carregaPaginas () {
      CarregaItens.getPaginas($routeParams.id)
      .success(function (data) {
        $scope.paginas = data;
      })
  };

  carregaPaginas();

});

.service('CarregaItens', function ($http) {

  getInfoPage = function (id) {
    return $http.get("http://www.meusite.com.br/api/paginas.php?id=" + id);
  };

  return {
    getPaginas: getInfoPage
  }

});
    
26.02.2016 / 21:19