How to create a query form with Angular?

0

Person, how do I create a form with some fields to query for example: Name and Phone and a Query button to send this data to the backend query and display in another view the return in a PivotTable.

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, however in my table the backend data appears but also "No record was found" .

On my system I have the form with the fields linked to the Controller DataCtrl and when I click on check my Service calls another route with another Controller ListDatasCtrl.

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

I do not know if using a controller to send and another 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 for simplicity.

// 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 the data that I will send to the backend to the service.

//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 a vector 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, I call the service again to give a getItem and fetch the data it 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;
              }

          });

        }

    }]);
});

On this controller above, I'm just doing a SIMULATION, if I pass the value 123 it does a GET and performs the fetching of data from some clients.

At the moment I made the setItem in the 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 search for the data always occurs normally, the get works blab, but unfortunately only occurs once. If I go back in the query form and click 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 it says "No record was found"

Perhaps there is another, simpler way to build what I need. Thanks in advance.

    
asked by anonymous 28.09.2015 / 21:01

1 answer

1

See if the example below caters to you. In my view it is friendlier besides using some of the best features available with angular (sort 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><linkrel="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>
    
30.09.2015 / 03:02