Problem when rescuing form data in Angularjs

Asked

Viewed 294 times

0

I have a mobile app I have a form that makes a filter by districts and municipalities what happens and that is not to rescue the selected data at home select the button pressed or doing anything.

Controller

.controller('FiltraEstabelecimentos', function($scope, $http, $stateParams) {
    $scope.BtnFiltraCat= function (campo){
        $http.post("https://www.sabeonde.pt/api/api_filtra_estabelecimentos.php?distrito=" + campo.distrito + "&concelho=" + campo.concelho + "&categoria=" +$stateParams.catSlug).success(function (data) {
            $scope.filtra_estabelecimentos = data;
        });
    };
})

View

<div ng-controller="FiltraEstabelecimentos">
        <form>
            <div class="row">
                <div class="col">
                    <label ng-controller="ListaDistritos" style="border-radius: 10px; margin: 0px 0px 10px 0px;" class="item item-input item-select">
                        <div class="input-label">
                            Distrito
                        </div>
                        <select ng-model="campo.distrito">
                            <option ng-repeat="lista_distritos in distritos" value="{{lista_distritos.id}}">{{lista_distritos.titulo}}</option>
                        </select>
                    </label>
                    <label ng-controller="ListaConcelhos" style="border-radius: 10px;" class="item item-input item-select">
                        <div class="input-label">
                            Concelho
                        </div>
                        <select style="border-radius: 10px;" ng-model="campo.concelho">
                            <option ng-repeat="lista_concelhos in concelhos" value="{{lista_concelhos.titulo}}">{{lista_concelhos.titulo}}</option>
                        </select>
                    </label>
                </div>
            </div>
            <div style="margin:0px 10px 0px 10px;">
                <button type="submit" ng-click="BtnFiltraCat(campo);" style="background-color: #CA5B60; border:#CA5B60; border-radius: 10px;" class="button button-block button-positive">
                    <i class="ion-search"></i> Pesquisar
                </button>
            </div>
        </form>  
    </div> 
  • Could make a console.log(data) and post the displayed object? data in question contains in one of the attributes the result of the request.

  • If you take the fields that you select and leave only the category with you the button works and I can save the category if you have them there the button does not work

  • Is not happening $scope as a parameter in the method, $scope belongs to the controller.

  • So as I do ?

  • Scope is this controller.

  • Yes, but then how I do I don’t understand

  • just remove it from the controller parameter and see if it worked.

  • Removed looked like this BtnFiltraCat= function (campo){ } and it doesn’t work

  • You do not need to remove the $Scope. variable from your method $scope.BtnFiltraCat = function(){ ... }. You can even run Scope on the controller, but I don’t think you need to. But the problem is that you have to get $Scope.campo.district in your controller.

  • I’ll give you an answer, and then you test, blz.

  • okay I wait

  • I posted it there, see if it rolled.

  • I tested but did not list either the districts or the counties

Show 8 more comments

2 answers

0

Good afternoon, try to take the semicolon out of ng-click and select options use ng-options instead of ng-repeat. And you also put the <label ng-controller="ListaConcelhos"... this controller as variable controller campo It would be interesting if these internal controllers were functions within the controller FiltraEstabelecimentos, so he recognizes every body in your view. Why when you declare controllers and use variables within them this variable will be handled by that controller and not by others.

A basic example of ng-options:

index.html (no file needed to download)

<html ng-app="teste">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" >
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7 /angular.min.js"></script>
<script src="app.js"></script>

<title>teste</title>
</head>

<body>
<nav ng-controller="controllerTeste">
    <div>
        <div>
            <select ng-model="campo" ng-options="lista_distritos.nome for lista_distritos in distritos" ng-change="mostrar()"/>
        </div>
    </div>
</nav>

</body>
</html>

app js.

angular.module('teste',[]).controller('controllerTeste', function($scope, $http){
$scope.distritos = [{
        nome : 'teste',
        cod : 1
    },{
        nome : 'teste2',
        cod : 2
    },{
        nome : 'teste3',
        cod : 3
    }];
$scope.mostrar = function(){
    alert($scope.campo.nome);
};


});
  • with ng-options do not list me data

  • Since you are using ng-options, it would look something like <select ng-model="field.district" ng-options = "list_districts.name in list_districts for districts">

  • Do not show anything can make an example of code based on what I have

  • Great ready I put in the answer a basic example of ng-options

0


First create a service:
OBS: From what I noticed, you sent the url by passing parameters via get and not post. So I set it as a method get.

//inicio do serviço
.factory('FiltroEstabelecimentos', ['$http',
            function ($http) {
              //construtor do serviço
              function FiltroEstabelecimentos() {
                var self = this;
                   //método que recebe os parâmetros para retornar a requisição em um promise
                    self.getEstabelecimentos = function(params) {

                          var promise;
                          var distrito = params.distrito;
                          var concelho = params.concelho;
                          var categoria = params.categoria;
                          var url = 'https://www.sabeonde.pt/api/api_filtra_estabelecimentos.php?distrito=' + distrito + '&concelho=' + concelho + '&categoria=' + categoria;
                          //método get
                          promise = $http.get(url);
                          //retorno da coleção
                          return promise;

              };
           } //instancia o serviço, permitindo chamar seus métodos no controller
              return new FiltroEstabelecimentos();
}])
.factory('AllEstabelecimentos', ['$http',
            function ($http) {
              //construtor do serviço
              function AllEstabelecimentos() {
                var self = this;
                   //método que recebe os parâmetros para retornar a requisição em um promise
                    self.getAllEstabelecimentos = function() {
                          var promise;
                          var url = 'https://www.sabeonde.pt/api/api_filtra_estabelecimentos.php?all';
                          //método get
                          promise = $http.get(url);
                          //retorno da coleção completa
                          return promise;
              };
           } //instancia o serviço, permitindo chamar seus métodos no controller
              return new AllEstabelecimentos();
}]);

Then in your controller, use the service created:

       //inicia o controller
        .controller('FiltraEstabelecimentos', ['$scope','$http','$stateParams', 'FiltraEstabelecimentos', 
              function($scope, $http, $stateParams, FiltraEstabelecimentos, AllEstabelecimentos) {
                  /* injeta o serviço que traz todos
                     os estabelecimentos 
                     (OBS: método que trás todos os dados,
                      sem passar parâmetros) */
                  $scope.campo = AllEstabelecimentos.getAllEstabelecimentos();
                  $scope.filtra_estabelecimentos = [];

                  $scope.$watch('distrito',function(newVal, oldVal) {
                        $scope.campo.distrito = newVal;
                  },true);
                  $scope.$watch('conselho',function(newVal, oldVal) {
                        $scope.campo.concelho = newVal;
                  },true);

                  $scope.BtnFiltraCat = function () {
                          if ($scope.campo.distrito != null && $scope.campo.concelho != null && angular.isDefined($stateParams.catSlug)) {
                              var data = {
                                           distrito:$scope.campo.distrito,
                                           concelho:$scope.campo.concelho,
                                           categoria:$stateParams.catSlug
                                         };
                              $scope.filtra_estabelecimentos = FiltraEstabelecimentos.getEstabelecimentos(data);  
                          }
                  };
}]);

In your view, I refactored to separate better, since you are using 3 controllers, not to confuse the origin of the method and its respective control:

  <div ng-controller="FiltraEstabelecimentos as ctrl1">
            <form>
                <div class="row">
                    <div class="col">
                        <label ng-controller="ListaDistritos as ctrl2" style="border-radius: 10px; margin: 0px 0px 10px 0px;" class="item item-input item-select">
                            <div class="input-label">
                                Distrito
                            </div>
                            <select ng-model="distrito">
                                <option ng-repeat="lista_distritos in ctrl2.distritos" value="{{lista_distritos.id}}">{{lista_distritos.titulo}}</option>
                            </select>
                        </label>
                        <label ng-controller="ListaConcelhos as ctrl3" style="border-radius: 10px;" class="item item-input item-select">
                            <div class="input-label">
                                Concelho
                            </div>
                            <select style="border-radius: 10px;" ng-model="concelho">
                                <option ng-repeat="lista_concelhos in ctrl3.concelhos" value="{{lista_concelhos.titulo}}">{{lista_concelhos.titulo}}</option>
                            </select>
                        </label>
                    </div>
                </div>
                <div style="margin:0px 10px 0px 10px;">
                    <button type="submit" ng-click="ctrl1.BtnFiltraCat();" style="background-color: #CA5B60; border:#CA5B60; border-radius: 10px;" class="button button-block button-positive">
                        <i class="ion-search"></i> Pesquisar
                    </button>
                </div>
            </form>  
        </div> 
  • Give this console error "Error: [$injector:unpr] Unknown provider: FiltraEstabelecimentosProvider <- FiltraEstabelecimentos <- FiltraEstabelecimentos

  • Do not forget to put the service in the footer of your layout. I just reissue, any error is good review, because I have not tested... I did in race.

  • does not list districts or councils

  • services comes before the controller.

  • yes and this before

  • Dude, you’re looking to list, but you need to send a parameter to this, where you arrow the parameters?

  • on two controllers I have

  • First you have to submit the full url, then filter.

  • The service is correct, it will work as soon as you send the parameters, but where is null, it has to be your data injection $scope.campo = {&#xA; distrito:null,&#xA; concelho:null&#xA; };

  • Basically, that would be your other service.

  • Okay I’ll test then

  • To list you do not need a filter, just put the direct return of a collection, it is a unique url, now if you want to filter your data, then you have to get, or post the data.

  • Great you have also tested if the api you are trying to access is returning values, what might be happening is this, takes the url you are using and tests in the browse, it should return something other than null

Show 8 more comments

Browser other questions tagged

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