I have a select element in my angular app tied to a model. When I change the model angular, for some reason, adds an extra option with value="?". Here is a jsFiddle to illustrate my point. Why is this happening and how can it be avoided?
angular.module('angularApp', []);
function testCtrl($scope, $timeout)
{
$scope.options = [1,2,3];
$scope.initialSelectedValue = 2;
$timeout(function(){
$scope.options = [4,5,6];
}, 3000)
}
<div ng-app="angularApp">
<div ng-controller="testCtrl">
<select ng-model="initialSelectedValue" ng-options="option for option in options"></select>
</div>
</div>
EDIT: I know I can simply add an option with value="" as a quick fix, but in my case I can't not have this option.
It's happening because you are changing the list in the middle, and the ViewModel initialSelectedValue
(which is poorly named, since it's not just the initial, but the actual current selected value) is left hanging, not pointing to any valid option of the select
.
This is done so that the model doesn't change "under the covers", and could only be set/changed explicitly, either by the controller, or by the change in the input.
To fix this, simply change the model to one of the available options when you change the list:
$scope.options = [1,2,3];
$scope.selectedValue = 2; // I changed the name
$timeout(function(){
$scope.options = [4,5,6];
$scope.selectedValue = $scope.options[0];
}, 3000)