0
votes

I have a form with a select, generated via ng-options and hooked up with a ng-model. This select calls a function via ng-change.
In this function I remove the selected option from the select and reset the value in the referenced ng-model to the default value.
On a later point I want to add this option back into the select, which works fine, but when adding the option to the select it automatically selects it, instead of the default value, that is already selected.
This seems to happen after the function adding the option finished and angular is running its internal $apply function.
How can I keep the default value selected?

html:

<select ng-model="selectedItem" ng-options="item.name for item in allItems" ng-change="selectItem(selectedItem)">
  <option value="">default</option>
</select>

angularjs:

$scope.selectItem = function(selectedItem) {
  $scope.allItems.splice( $scope.allItems.indexOf(selectedItem), 1 );
}

$scope.addItem = function(item) {
  // $scope.selectedItem == "";
  $scope.allItems.push(item);
  // $scope.selectedItem == "";
}
1
Put up sample code, or a fiddle/plunkr?deitch
Could you check before you add the old option back in read the select to see which option is currently selected. Add your old option back in, and then just re-select the previous value that was selected - that you just read?Code Uniquely
The selected value is null (default) before and after I add the new option. But gets changed when angulars apply function fires.Alex Doe
I added some sample code.Alex Doe

1 Answers

1
votes

Your ng-model defines what is selected. So try to assign the default value to it when you add again new values to the select option and see if it works.

Edit: Remember, it has to be 0 (zero), not " ".

Instead of

$scope.selectedItem = ""

Try assigning zero, like

$scope.selectedItem = 0

Here's a working fiddle demo.