How to create a query form with Angular?

Asked

Viewed 2,878 times

0

Person, as I create a form with some fields for consultation for example: Name and Phone and a Query button to send this data to the backend to query and display in another View the return in a dynamic table.

I can do this using Service normally, but it only works once, when I try to perform the same query the data is returned to my View, but in my table appear the backend data but also appears "No record was found".

On my system I have the form with the fields linked to the Data Controller and when I click to consult my Service calls another route with another Data Controller.

As I said, the data is brought in normally but only works the first time.

I don’t know if using a controller to send and another controller to list is the best way.

Does anyone have any idea how I can create this form for queries?

Follow the code I’m trying to do. I’ve modified a few things to simplify.

// View com Form de Consulta
<form name="frmClientesConsulta">
    <div class="row cells4">
        <div class="cell">
            <label>Nome:</label>
            <input type="text" class="input-control text" ng-model="dadclientes.nome">
        </div>
        <div class="cell colspan2">
            <label>Telefone:</label>
            <input type="text" class="input-control text" ng-model="dadclientes.telefone">
        </div>
        <div class="cell">
            <button ng-click="buttonExecute('consultar')">Consultar</button>
        </div>
    </div>
</form>

By clicking the button it performs the function below to send to the service the data I will send to the backend query

//Controller DadosCtrl
define(['app'], function (app) {
    'use strict';

    app.controller('DadosCtrl', ['$scope','$location','dadosCliente', function ($scope,$location,dadosCliente) {

        $scope.dadclientes = [];

        $scope.buttonExecute = function (nameAction) {
              if (nameAction == 'consultar') {
                dadosCliente.setItem($scope.dadclientes);
              } else if (nameAction == 'limpar') {
                $scope.dadclientes = [];
              };
        };


    }]);
});

Button calls the service below to set the values in one array to be passed to the other controller (Listdadosctrl)

// Service dadosClientes
define(['app'], function (app) {
    'use strict';

    app.service('dadosClientes', function dadosClientes($location) {
        var dados = [];
        return {
            getItem: function () {
                return dados;
            },
            setItem: function(value) {
                dados = value;
                $location.path('/dados/list_clientes'); // Essa Rota irá apontar para a VIEW que possui a tabela dinamica e o Controller (ListDadosCtrl)
            }
        };

    });

});

When calling the controller below, call again the service to give a getItem and fetch the data that were submitted in the form.

//Controller ListDadosCtrl
define(['app'], function (app) {
    'use strict';

    app.controller('ListDadosCtrl', ['$scope','$location','dadosClientes', function ($scope,$location,dadosClientes) {

        var dados = [];
        $scope.clientes = [];
        dados = dadosCliente.getItem();

        if (dados.telefone == "123") {

          $http.get('http://localhost:3000/clientes').success(function(data) {

              if (data.length > 0) {
                $scope.clientes = data;
              }

          });

        }

    }]);
});

In this controller above, I’m only doing a SIMULATION if I pass the phone value 123 it makes a GET and performs data search of some clients.

By the time I set it in Service, I already used $Location to trigger the other view where the data will be displayed.

// View com Tabela Dinâmica que recebe os dados do BackEnd
<table class="dataTable"
       data-role="datatable"
       data-searching="true"
       data-paging="true"
       data-language="{{language}}">
    <thead>
        <tr>
            <th>ID</th>
            <th>NOME</th>
            <th>TELEFONE</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="cliente in clientes">
            <td>{{cliente.id}}</td>
            <td>{{cliente.nome}}</td>
            <td>{{cliente.telefone}}</td>
        </tr>
    </tbody>
</table>

As I commented in the original post, the data search always occurs normally, the get works blazinha, but unfortunately only occurs once. If I go back in the query form and click on the button again, the data is displayed in the table but because it is a Datatable, the table does not understand that it has records and puts the message "No record was found"

Perhaps there is another way much simpler to build what I need. I thank you in advance.

  • Without seeing your code becomes difficult to help, post it too

  • Emir, thank you for evaluating... I already put the code, I hope you can understand. VLW

  • Came to debug to see if your service no longer returns?

  • So the service is always working... and returns the data every time. The point is that in my view where the table is... only in the first query is it populated correctly... when I go back in the form and ask for the same data... the table is populated but keeps the information of no record found. So I’m seeing if it’s possible to do this another way for me to try to continue using my datatable normally.

  • This no record info found is a treatment you do?

  • Got it + or - what do you want to do. A screen to filter information is this? You have several ways to do this. Confirm that I put a suggestion that would be simpler

  • Oops... the information of no record is actually a treatment of an api I picked up from the internet http://datatables.net and even when I populate my array of clients to use with ng-repeat on the table ends up appearing that it has no record, but anyway, the idea is what you really said. A screen to filter records... but the question is that the result should be shown in a view other than the view where the form with the filters is. If you have an example thank you too much. Thank you again.

  • Ever heard of the angular filter? It wouldn’t help you?

  • Yes, I have.. but I honestly could not think of any way to use it in order to assemble the form I need. You have some different idea?

  • Could inform in more detail the pq of the need for two views?

  • Well... I’m migrating the somewhat old system that was in php and in it we had this behavior. On one page I have the form and when sending query the form data, it directed to another page with the results displayed in a table, but if you have a better suggestion it may be interesting to use. Like I said, I don’t know if I’m going the right way trying this approach.

  • I have a suggestion yes, but I will get mount it only at the end of the day. It may be?

  • Opa... that this guy... you are already helping me too much. Of course you can!!! if you want to send to my email, you can send also. [email protected]. Thank you

  • Take a look here and see if it helps. In this example I make a sroll-infinity with angular and java: https://github.com/emirdeliz/meus-projects/tree/master/scroll-infinito-angular-rest-datafactory/src/main/webappassets/js

  • Otherwise the night I do something closer to your example

  • Emir, I’ve seen your example and he’s very nice, but I still believe that’s not the way. I re-evaluated my code and saw a flaw in the moment of popular my $Scope.clientes. I didn’t remember to put it in the post but I use some generic screens through ng-template, so for each different screen I have a property in my controller where I inform which view will be loaded. Ex.: $Scope.viewname = 'list-customers' but only that I was assigning the value before GET in the backend. now put after the assignment of $Scope.customers = date and it looks like it worked.

  • If you still want to send me some other model so I can evaluate... I am very grateful and I thank you again for all your attention. Vlw very much.

  • Blz, tonight I take a look

Show 13 more comments

1 answer

1

See if the example below suits you. In my view it is friendlier besides using some of the best features available with angular (sorting and table filter).

var clienteApp = angular.module("ClienteApp", []);
clienteApp.factory("$servicoGenerico", function($http, $q) {
  function ajax(url, parametros, metodo) {
    var requisicao = $http({
      method: metodo,
      url: url,
      data: parametros
    });

    var promessa = requisicao.then(function(resposta) {
        return (resposta.data);
      },
      function(resposta) {
        return ($q.reject("Something went wrong"));
      }
    );
    return promessa;
  }
  return ({
    ajax: ajax
  });
});

clienteApp.factory("$cliente", function($servicoGenerico) {
  return {
    consultarPorNomeTelefone: function(nome, telefone) {
      var promessa = $servicoGenerico.ajax("<url consulta back-end>/" + nome + "/" + telefone, "", "<metodo consulta(POST, GET, ETC...)>");
      return promessa;
    }
  };
});

clienteApp.controller("ClienteController", function($scope, $cliente) {
  $scope.ordenacao = "nome";
  $scope.ordenacaoReversa = "false";

  $scope.consultar = function() {
    /* Aqui simularia a consulta no back-end */
    //$scope.cliente = $cliente.consultarPorNomeTelefone($scope.nome, $scope.telefone);

    /* Colocando um mock para simular comportamento */
    $scope.cliente = [{
      nome: "SSA Comunicações",
      telefone: "(47)8899-6788",
      cidade: "Rio do Sul"
    }, {
      nome: "Argoville",
      telefone: "(47)3465-5435",
      cidade: "Joinville"
    }, {
      nome: "Brahma",
      telefone: "(51)4367-9877",
      cidade: "Joinville"
    }, {
      nome: "Antartica",
      telefone: "(67)8977-6655",
      cidade: "Blumenau"
    }, {
      nome: "Stackoverflow",
      telefone: "(77)8644-3334",
      cidade: "Jaraguá do Sul"
    }];
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">


<div class="container" ng-app="ClienteApp" ng-controller="ClienteController">
  <div class="form-group">
    <div class="input-group">
      <label>Nome:</label>
      <input type="text" class="form-control" ng-model="nome">
      <a href="#" class="btn btn-sucess btn-sm" ng-click="consultar();">Buscar</a>
    </div>
    <div class="input-group">
      <label>Telefone:</label>
      <input type="text" class="form-control" ng-model="telefone">
      <a href="#" class="btn btn-sucess btn-sm" ng-click="consultar();">Buscar</a>
    </div>
  </div>

  <br>
  <div class="alert alert-info">
    <p>Sort Type: {{ ordenacao }}</p>
    <p>Sort Reverse: {{ ordenacaoReversa }}</p>
    <p>Search Query: {{ filtro }}</p>
  </div>
  <div class="form-group">
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-search"></i>
      </div>
      <input type="text" class="form-control" placeholder="Filtrar" ng-model="filtro">
    </div>
  </div>
  <table class="table table-bordered table-striped">
    <thead>
      <tr>
        <td>
          <a href="#" ng-click="ordenacao = 'nome'; ordenacaoReversa = !ordenacaoReversa">
                        Nome
                        <span ng-show="ordenacao == 'nome' && !ordenacaoReversa" class="fa fa-caret-down"></span>
                        <span ng-show="ordenacao == 'nome' && ordenacaoReversa" class="fa fa-caret-up"></span>
                    </a>
        </td>
        <td>
          <a href="#" ng-click="ordenacao = 'telefone'; ordenacaoReversa = !ordenacaoReversa">
                        Telefone
                        <span ng-show="ordenacao == 'telefone' && !ordenacaoReversa" class="fa fa-caret-down"></span>
                        <span ng-show="ordenacao == 'telefone' && ordenacaoReversa" class="fa fa-caret-up"></span>
                    </a>
        </td>
        <td>
          <a href="#" ng-click="ordenacao = 'cidade'; ordenacaoReversa = !ordenacaoReversa">
                        Cidade
                        <span ng-show="ordenacao == 'cidade' && !ordenacaoReversa" class="fa fa-caret-down"></span>
                        <span ng-show="ordenacao == 'cidade' && ordenacaoReversa" class="fa fa-caret-up"></span>
                    </a>
        </td>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in cliente | orderBy:ordenacao:ordenacaoReversa | filter:filtro">
        <td>{{ item.nome }}</td>
        <td>{{ item.telefone }}</td>
        <td>{{ item.cidade }}</td>
      </tr>
    </tbody>
  </table>
</div>

Browser other questions tagged

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