2

As I understand AngularJS sets default value when using ng-model directive. I need to populate select element with only valid options which retrieved by $http.get. The problem is that on top of all valid elements I have one dummy element vith value ?. How to get rid of it?

<select  id="environment" name="environment_name" ng-model="environment"  ng-options="e.name for e in ENVIRONMENTS" required>
                </select>

$scope.ENVIRONMENTS = [];
$http.get("/getEnvironments").success(function(data){
       data.forEach(function(el){
           $scope.ENVIRONMENTS.push(el);
       });
    }).error(function (data) {
        $scope.showErrorMsg("Cannot get ENVIRONMENTS.");
    });
 $scope.environment = $scope.ENVIRONMENTS[0];
J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
  • Seems like this is relevant: http://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select – Ivan Chernykh Nov 10 '14 at 13:24

1 Answers1

3

You can add temporary value to your $scope.ENVIRONMENTS array ie:

 $scope.ENVIRONMENTS = [{name:"Please wait"}];

and delete it after you get data from your backed

$scope.ENVIRONMENTS.shift()

Please see demo below

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope, $http) {


  $scope.ENVIRONMENTS = [{
    name: "Please wait"
  }];
  $http.get("/getEnvironments").then(function(data) {
    $scope.ENVIRONMENTS.shift()
    data.forEach(function(el) {

      $scope.ENVIRONMENTS.push(el);
    })

   //set default value after you get data from backend
   $scope.environment = $scope.ENVIRONMENTS[0];

  }, function(data) {

    $scope.showErrorMsg("Cannot get ENVIRONMENTS.");
  });
  $scope.environment = $scope.ENVIRONMENTS[0];

  $scope.showErrorMsg = function(msg) {

    console.log(msg);

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">
    
    <select id="environment" name="environment_name" ng-model="environment" ng-options="e.name for e in ENVIRONMENTS" required>
    </select>
  </div>
</div>
sylwester
  • 16,498
  • 1
  • 25
  • 33