How to load dropdown list using Angularjs and php

Asked

Viewed 1,188 times

0

I was able to load a drop-down using php. Now I need to load the second drop-down, based on the selection of the first.

Someone knows how to do it?

Thanks.

<body ng-app="app" ng-controller="statecontroller">
<label>Categorias</label>
<select ng-model="categoria">
    <option value="">Selecione</option>
    <option ng-repeat="x in categorias" value="{{ x.id_categoria }}">{{ x.categoria }}</option>
</select>

<label>Subcategorias</label>
<select ng-model="subcategoria">
    <option value="">Selecione</option>
    <option ng-repeat="x in subcategorias" value="{{ x.id_subcategoria }}">{{ x.subcategoria }}</option>
</select>

<script src='js/angular.min.js'></script>
<script>
var app = angular.module("app",[]);
app.controller("statecontroller", ['$scope', '$http', function ($scope, $http) {
    $http.get("php/carregaCategorias.php").success(function(response) {
        $scope.categorias=response;
    });
}]);
</script>

Primeiro drop-down funcionando

  • 1

    Add the code.

  • I don’t have code @Diegofelipe

  • Gustavo, do the same thing for function uploadCategories.

  • Even though this part is working?

  • Dude, I said shit. I’m sorry. I’m not moving. LOL. What’s the status now? What’s going on?

  • Ta the way it is in the description. See above Cleiton

  • Hey, guys, any more tips?

  • 2

    It includes a workable solution in my question, it also follows a link to a Fiddler https://jsfiddle.net/ybjpvopn/, I hope it helped.

Show 3 more comments

2 answers

1

Do not request using $.http of jQuery, it rotates outside the 'environment' of angular which forces you to update the $scope. In your example, to make it work, simply encapsulate the signature of the value in the method $apply of Scope.

Following example:

    $.post( urlService, data, function( response ) {
        if ( typeof response.cidades === 'undefined') {
            // Código para tratar erro
        }

        // Receber cidades enviados pelo PHP no formato
        // array( array('id'=>XXX,'nome'=>'yyyy', ...), ...)
        $scope.$apply(function(){ $scope.cidades = response.cidades;})
    });

A complete sample solution follows below:

https://jsfiddle.net/ybjpvopn/

(I didn’t post directly here at stackoverflow because you’re still in trouble)


I advise that, when you have time, read the guidelines of the Angularjs community, since it teaches some basic rules on code design and rules on separation of responsibilities.

An important resource is that maintained by John Pope (https://github.com/johnpapa/angular-styleguide )

  • See if this is the change I made in the code, here in the post, that you suggest I make Cleiton.

  • Dude, $http is an angular... https://docs.angularjs.org/api/ng/service/$http

  • @david, he changed the question. Reread my answer. I didn’t understand the -1.

  • I had some problems with the $http. When I consulted between different domains, I had to change the header in PHP Access-Control-Allow-Origin. I also had problems with sending images. Not that I could not solve, but with jquery is simpler, so I prefer.

  • @Cleiton I have now identified, so instead of using the apply it would be more correct to use the $http.post('/someUrl', data, config).then(successCallback, errorCallback); as the angular will detect the change in scope and function properly.

  • Hey, guys, any more tips?

  • Wouldn’t it be better to inject the API and use it instead of pure http

Show 2 more comments

0

HTML code:


<html>
    <head>...</head>
    <body ng-app = 'app'>
        <div ng-controller='MainController'>    
            <div class="form-group">
                <label for="estado">Estado</label>
                <select
                 id         = 'estado'
                 name       = 'estado'
                 ng-model   = 'ufSelecionado'
                 ng-options = '
                    estado.uf                       as
                    estado.uf + " - " + estado.nome for
                    estado                          in
                    estados'
                 ng-change  = 'listarCidades( ufSelecionado )'
                 required
                 >
                    <option value=''>[SELECIONE]</option>
                </select>
            </div>
            <div class="form-group">
                <label for="cidade">Cidade</label>
                <select
                 id         = 'cidade'
                 name       = 'cidade'
                 ng-model   = 'cidade'
                 ng-options = 'cidade.id as cidade.nome for cidade in cidades'
                 required
                 />
            </div>
        </div>
    </body>
    <script src='[caminho_do_jquery]/jquery.min.js'></script>
    <script src='[caminho_do_angular]/angular.min.js'></script>
    <script>
        // Receber estados do PHP e passar para o javascript
        // como uma array no formato array('uf'=>'nome do estado', ...)
        var estados = <?= json_encode( $estados ) ?>;
    </script>

Javascript code:

var dependencias = []; // Declare suas dependências
var App = angular.module( 'App', dependencias );

App.controller( 'MainController', function( $scope ) {

    // Integrar no AngularJs os estados do javascript
    $scope.estados  = estados;
    $scope.cidades  = null;

    // Função para carregar as cidades
    $scope.listarCidades = function( uf ) {
        var urlService  = '...'; // Digite a URL do serviço
        var data        = {
            uf          : uf,
        };

        $.post( urlService, data, function( response ) {
            if ( typeof response.cidades === 'undefined') {
                // Código para tratar erro
            }

            // Receber cidades enviados pelo PHP no formato
            // array( array('id'=>XXX,'nome'=>'yyyy', ...), ...)
            $scope.cidades = response.cidades;
        })
        .error( function() {
            // Código para tratar erro
        });
    }
});
  • I’ll try @Marciojalber

  • Can I use Jquery together with Angularjs?

  • I’m able to bring the data, but I’m not getting popular in the first dropdown.

  • You can use jquery and angular without any problem. But you should call jquery first. Even the angular encapsulates some basic functions of jQuery through the syntax angular.element( '#element' )....

  • @Gustavosevero, show me your code so I can evaluate and point out where the problem might be.

  • Ta similar to your.

  • I realized a mistake and changed the answer: in the definition of date, I was passing $scope.uf, when was to pass Uf received as Function parameter. Please change and tell me if it worked.

  • The same, nothing has changed. See how is my code, in the description of this post. It pulls the data correctly, but is not populating the first drop-down.

  • @Gustavosevero, note that in the definition of the variable datawhich is sent to <Strong>php/loadSubcategories.php</Strong>, you must change from uf : $scope.uf, for uf : uf.

  • @Gustavosevero, another thing. Add after the line $scope.subcategorias = response.subcategorias; the instruction $scope.$digest();, so that the angular updates the information in the view, as it was received asymptotically.

  • I made the modifications Marcio Jalber, but it’s still the same.

  • Gives a console.log( response ); to see what is returning from your service php/carregaSubcategorias.php.

  • Nothing, nothing came up.

  • I don’t think it’s gonna work because the first drop-down isn’t being loaded, you know? The data from the php flame comes, but they are not populating the drop-down, you know? As I show in the image I posted here.

  • Hey, guys, any more tips?

Show 10 more comments

Browser other questions tagged

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