Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Created February 23, 2017 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandreaquiles/05bac49859935b98733656cee7659b4e to your computer and use it in GitHub Desktop.
Save alexandreaquiles/05bac49859935b98733656cee7659b4e to your computer and use it in GitHub Desktop.
Exemplo de selects aninhados com AngularJS 1
angular.module('alurapic')
.controller('EstadosController', function($scope, $http) {
$http.get('/v1/estados')
.success(function(estados) {
$scope.estados = estados;
});
$scope.escolheuEstado = function() {
$scope.cidadeEscolhida = undefined;
console.log($scope.estadoEscolhido);
if($scope.estadoEscolhido) {
$http.get('/v1/estados/' + $scope.estadoEscolhido + '/cidades')
.success(function(cidades) {
$scope.cidades = cidades;
});
}
}
});
<div class="form-group">
<label>Estados</label>
<select ng-change="escolheuEstado()" class="form-control" ng-model="estadoEscolhido" ng-options="estado.sigla as (estado.nome) for estado in estados">
<option value="">Escolha um estado</option>
</select>
</div>
<div class="form-group">
<label>Cidades</label>
<select class="form-control" ng-model="cidadeEscolhida" ng-options="cidade.id as (cidade.nome) for cidade in cidades">
<option value="">Escolha uma cidade</option>
</select>
</div>
<p class="alert alert-success" ng-show="estadoEscolhido && cidadeEscolhida">{{cidadeEscolhida + ' - ' + estadoEscolhido}}</p>
<script src="js/controllers/estados-controller.js"></script>
$routeProvider.when('/estados', {
templateUrl: 'partials/estados.html',
controller: 'EstadosController'
});
app.get('/v1/estados', function(req, res) {
var estados = [ {sigla: 'DF', nome: 'Distrito Federal'},
{sigla: 'RJ', nome: 'Rio de Janeiro'},
{sigla: 'SP', nome: 'São Paulo'} ];
res.json(estados);
});
app.get('/v1/estados/:estado/cidades', function(req, res) {
var cidades = {
DF: [{id: 1, nome: 'Brasília'}],
RJ: [{id: 2, nome: 'Angra dos Reis'}, {id: 3, nome: 'Rio de Janeiro'}],
SP: [{id: 4, nome: 'Araraquara'}, {id: 5, nome: 'Campinas'}, {id: 6, nome: 'Jacareí'}, {id: 7, nome: 'São Paulo'}]
};
res.json(cidades[req.params.estado]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment