Mars Mars - 4 months ago 35
AngularJS Question

Angular ng-options display data from database

//EDIT Solution
the code its ok, the problem was materialize select, doesnt work with angular dinamic elements :(

Hello im trying to display data in a select tag with angular
i read a lot but i cannot solve this problem. as you can see with test code works but with the function does not, need help thanks

this is the json that php file returns

{"records":[{"numero":"312312"},{"numero":"31221111"},{"numero":"311241"},{"numero":"112441"},{"numero":"11312"},{"numero":"131"}]}


my controller

app.controller('chequeoCtrl', function($scope, $http){
//with this function do not work
$scope.leerNumero = function(){
$http.get("objetos/autoelevador/leer_numero.php").success(function(response){
$scope.data = response.records;
console.log($scope.data);
});
};
$scope.leerNumero();

// with this array works, just for test!!
/*$scope.names = [{"name":"pepe"},{"name":"pepe2"}];
console.log($scope.nombres); */


})

My
select
tag:

<select ng-model="autoelev" ng-options="item.numero as item.numero for item in data">
<option value="" disabled selected>Seleccionar autoelevador</option>
</select>

Answer

Try code below, Demo here:

View:

<body ng-controller="MainCtrl">
  <select ng-options="item.numero for item in data" ng-model="chosen">
      <option value="" disabled selected>Seleccionar autoelevador</option>
  </select>
</body>

Controller:

angular.module('app', [])
  .controller('MainCtrl', function($scope, $http) {
    $http.get('data.json')
      .then(function(res) {
        $scope.data = res.data.records;
        console.log($scope.data);
      });
  })

Do $scope.data = response.data.records in your controller and make sure its an array of options.

console.log($scope.data) in your controller should print as below:

[{"numero":"312312"},{"numero":"31221111"},{"numero":"311241"},{"numero":"112441"},{"numero":"11312"},{"numero":"131"}
Comments