Passing a controller variable to a service

Asked

Viewed 869 times

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>
	  <div class="item item-body">
	    <h2 class="card-title">{{item.titulo}}</h2>
	  </div>
	</div>
</div>

Guys, I have this controller and this service that interact perfectly well, but what I need is for the.id item that is listed in the view to be sent to my service by replacing the static "4" of the API url. I’ve tried using $routeparams but when 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 doesn’t work (logical). Any idea?

2 answers

2


You should import the $stateParams and use the $stateParams.id. Also in the $http.get() you must use the object config to stay as shown below. This way it 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

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 it is giving error) and pass the Id as a parameter in the service. Something more or less 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
  }

});

Browser other questions tagged

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