There is a select drop-down on my page with three options: orange, banana, and mango. I have a button that allows me to add a new item to the list. When I have orange selected in the drop-down and click the add button to add a new fruit like peach, I end up seeing peach repeated twice. The existing selection of orange gets replaced with peach as well. I am using Angular.copy
as shown below, but I'm wondering why this duplication is happening. The list of fruits is fetched from the server, with a fruits arraylist in my action that is parsed as JSON to be displayed on the page.
<select id="fruitSelect" ng-options="fruit.description for fruit in fruits" ng-model="selectedFruit" ng-change="fruitsClicked()"> </select>
Additionally, I have a button that, when clicked, opens a modal asking the user to provide a name to save the fruit to the list.
<button type="button" ng-click="saveFruit()">Save</button>
The JS controller code:
$scope.saveFruit= function() {
var length = $scope.fruits.push({
description: angular.copy($scope.form.newFruit)
});
$scope.selectedFruit= angular.copy($scope.fruits[length-1]);
};
My intention is to select the newly added fruit in the drop-down by setting the ng-model
selectedFruit
to the angular copy value of the last saved fruit. While this method works fine, it results in a duplicate entry. It replaces the previously selected orange with peach in my scenario.