ajmajmajma ajmajmajma - 1 month ago 18
AngularJS Question

Angular, select list first item is empty

I am populating my select list like so -

<select class="selectLevel0" ng-model='scope1' ng-change='scope1Change()'
ng-options='obj.name for obj in array track by obj.id'>
</select>


Here is the $http behind it :

//populate scopes
$http.post("/listScopes").success(function(data){
$scope.array = data.scopes;
});


What is happening is - I am getting a first select item that has no name and a value="?" (the rest populate fine). I can't seem to figure out why it's doing this. Any help would be much appreciated. Thanks!

PSL PSL
Answer

Reason is that since your ngModel is most possibly not assigned or not assigned properly with the id, angular creates a blank option and display that as selected.

You could either add a default option:-

<select class="selectLevel0" ng-model='scope1' ng-change='scope1Change()' 
            ng-options='obj.name for obj in array track by obj.id'>
 <option value="">Please choose a level</option>
</select>

Or set your ngModel with a default value in your controller or set it in ng-init. I would do it in the controller:-

 $scope.scope1 = "id"
Comments