How popular dropdown 2 based on dropdown 1 with angular

Asked

Viewed 1,181 times

1

I want to use two dropdowns in my HTML5 As I select in dropdown 1, it displays the respective data in dropdown 2, as in this link I searched the documentation of the angle that that you’ve come very close, but it hasn’t worked out yet. NOTE: Both dropdown values, are loaded from the api in php, and not placed "at hand" as in the link I passed above

HTML5

<form>
    <label>Estabelecimento</label>
    <select class="form-control" name="estabelecimento" ng-model="mesa.idestabelecimento" required="required" ng-change="getUnidade()" ng-options="c as c.nome for c in cia track by c.idestabelecimento">
         <option value="">Selecione estabelecimento</option>
         <option ng-repeat="c in cia" value="{{ c.idestabelecimento }}" required>{{ c.nome }}
    </option>
    </select>
    <label>Unidade</label>
    <select class="form-control" name="unidadeMesa" ng-model="mesa.unidade" required>
        <option value="">Selecione unidade</option>
    </select>
    <label>Número da mesa</label>
    <input class="form-control" type="text" name="numeroMesa" ng-model="mesa.numero" placeholder="Número da mesa">
    <button class="btn btn-block btn-primary btnAdicionar" ng-click="adicionar(mesa)">Adicionar</button>
</form>

controller

app.controller("MesasCtrl", ['$scope', '$http', '$window', '$location', '$rootScope', function ($scope, $http, $window, $location, $rootScope) {

$rootScope.idestabelecimento = localStorage.getItem('idestabelecimento');

var buscarEstabelecimento = function(){
    var opcao = 1; //Buscar estabelecimento
    $http.get("http://localhost:8888/sistemas/Android/areaAdmin/api/admin_estabelecimento/mesa.php?opcao="+opcao).success(function(response){

        $scope.cia = response;

    })
}

buscarEstabelecimento();

$scope.getUnidade = function(){

    $scope.selected = $scope.idestabelecimento;
    var key = $scope.selected;
    console.log("key :"+$scope.selected)
}

}]);

And regardless of the value I select in the first dropdown, the value on the console is always the same: "key :4"

inserir a descrição da imagem aqui

  • You have two dropdown and you want one to load the other correct, but in your code you have repeat and options in the same dropdown... that’s what’s wrong.

  • Hello @Virgilionovic, both data loaded in the dropdowns comes from the backend... But I will try to use your example

  • Opa @Gustavosevero, where are you dropItens1 and dropItens2 if you load the information, only changes that the rest remains the same.

  • Yes, I tried this, but it didn’t work kkkkkkk I did the following: $Scope.dropItens1 = [{'value': Answer.idestablishment}, {'text': Answer.name}];

  • Can I generate an example could I understand with two Rest? dynamic data?

1 answer

0

To build a select what filter the next, is like this, minimal example:

var app = angular.module("app", []);
app.controller("ctrl", function($scope, $filter) {
  $scope.dropItens1 = [{
      'value': 1,
      'text': 'Tenis'
    },
    {
      'value': 2,
      'text': 'Roupa'
    }
  ];
  
  $scope.dropSelected1 = 1;
  $scope.dropSelected2 = {};
  
  $scope.dropItens2 = [{
      'value': 1,
      'text': 'Adidas',
      'item': 1
    },
    {
      'value': 2,
      'text': 'Olimpikus',
      'item': 1
    },
    {
      'value': 3,
      'text': 'Camiseta',
      'item': 2
    },
    {
      'value': 4,
      'text': 'Calça',
      'item': 2
    }
  ];
  
  $scope.selectChange = function()
  {
    console.log("Item Selecionado:" + $scope.dropSelected1);
  }
  $scope.selectChange();
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <select name="s1" ng-options="item1.value as item1.text for item1 in dropItens1" ng-model="dropSelected1" ng-change="selectChange()">  
  </select>

  <select name="s2" ng-options="item2.value as item2.text for item2 in dropItens2 | filter:{ item : dropSelected1 }" ng-model="dropSelected2">  
  </select>

</div>

Minimum example with database search

Tables

inserir a descrição da imagem aqui

Html

<!DOCTYPE html>
<html lang="en" ng-app="app">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">  
        <style>
            form.label {
                width: 150px;
            }
        </style>      
        <!--<link href="css/style.css" rel="stylesheet">-->        
    </head>
    <body ng-controller="indexCtrl"> 
    <div>
          <select name="s1" ng-options="item1.idestabelecimento as item1.nome for item1 in dropItens1" ng-model="dropSelected1" ng-change="selectChange()">  
          </select>

          <select name="s2" ng-options="item2.idunidade as item2.nome for item2 in dropItens2" ng-model="dropSelected2">  
          </select>
    </div>          
        <script src="js/angular.min.js"></script>        
        <script>
            var app = angular.module('app', []);

            app.controller("indexCtrl", ["$scope", "$http", function($scope, $http)
            {
                $scope.dropItens1 = [];
                $scope.dropSelected1 = 0;

                $scope.dropItens2 = [];        
                $scope.dropSelected2 = 0;

                $scope.selectChange = function()
                {
                    $scope.dropItens2 = [];
                    $scope.dropSelected2 = 0;
                    $http.get('rest.php?select=2&&id=' + $scope.dropSelected1)
                        .then(function($result){                            
                            $scope.dropItens2 = $result.data;
                            $scope.dropSelected2 = $result.data[0].idunidade;                            
                        });
                }

                $scope.init = function()
                {
                    $http.get('rest.php?select=1')
                        .then(function($result){                            
                            $scope.dropItens1 = $result.data;
                            $scope.dropSelected1 = $result.data[0].idestabelecimento;
                            $scope.selectChange();
                        });
                }
                $scope.init();
            }]);

        </script>
    </body>
</html> 

PHP

<?php

    function getConexao()
    {
        $dns = 'mysql:host=localhost;dbname=testdb';
        return new pdo($dns, 'root', 'senha');
    }

    $pdo = getConexao();

    function getEstabeleciomento($pdo)
    {
        $result = $pdo->query('SELECT * FROM `estabelecimento`', PDO::FETCH_ASSOC);
        $result->execute();
        return json_encode($result->fetchAll());
    }


    function getUnidade($pdo, $id = 0)
    {
        $result = $pdo->prepare('SELECT * FROM `unidade` where idestabelecimento=?');
        $result->bindValue(1, $id, PDO::PARAM_INT);
        $result->execute();
        return json_encode($result->fetchAll());
    }

    $select = isset($_GET['select']) 
        ? (int)$_GET['select']
        : 1;


    if ($select === 1) echo getEstabeleciomento($pdo);
    if ($select === 2) 
    {
        $id = $_GET['id'];
        echo getUnidade($pdo, (int)$id);
    }

Observing: this code can still be optimized, at first to have only one request, but, I left so that I can understand how it would work.

  • Cool! I tested it and it worked. However, I do not know how to make it work with my codes, because the data of the dropdowns comes from an api, are loaded dynamically understand? Look at the description of the post. I put the return of the api.

  • Set, I did this: $Scope.dropItens1 = [{ 'value': Sponse[0]. idestablishment, 'text': Sponse[0]. name }, { 'value': sponse[1]. idestablishment, 'text': sponse[1]. name }]; The problem is that I have to put "Response[0], Response[1]", otherwise it doesn’t work. How can I change this dynamically?

  • You have to list the names of yours in relation to mine, idestabelecimento = value, the return is also total in variable. @Gustavosevero

  • I just did that... It worked, BUT, as I told you in the previous message, I have to do it so that "Answer[0]. setting, "this zero position, be updated dynamically, do you understand? I can not update at hand.

  • @Gustavo ask what you did in your question my answer is generic because your question was also

  • See if it’s still generic for you. OBS: Write the sentence with commas so I can understand it more easily, OK?

  • It didn’t help @Gustavosevero, because I need to know what the two sends!

  • Virgilio, I posted an image, at the end of the description, that shows how is being returned this Rest. You saw the whole post?

  • Of course I saw @Gustavosevero, but the second rest one is for a drop and the other? or one is fixed?

  • I’m sorry, I don’t understand your question.

  • @Gustavosevero I made an edition and put with an example with dynamic search, Observer all points.

Show 7 more comments

Browser other questions tagged

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