I have a list of sale items and for each sale item there is a dropdown box where you can select from a list of available IDs to assign to the sale item. The selection must be unique for each sale item. If 2 is selected from saleItem1 dropdown, 2 cannot be available in the dropdown for saleItem2.
After selecting an ID from the dropdown list I need to remove it from the list and replace it with the old ID. Selecting an ID fires the ng-change which updates the list correctly. However the line marked with an asterix, which removes the selected ID from the list, causes ng-change to be fired again with a null value as the new ID.
I am struggling to find a solution to work around this.
The same code works fine in AngularJS 1.2, but after moving to 1.7 I am seeing this issue.
$scope.updateSaleItemIds = function(saleItem, newid) {
var ind = $scope.availableSaleItemIds.indexOf(newid);
if (!isNaN(saleItem.id)) {
*$scope.availableSaleItemIds[ind] = saleItem.id;*
}
else {
$scope.availableSaleItemIds.splice(ind,1);
}
$scope.availableSaleItemIds.sort(function(a, b){return a - b});
var indE = $scope.saleItems.indexOf(saleItem);
$scope.saleItems[indE].id = newid;
};
HTML
<tr ng-repeat="saleItem in saleItems" class="createForm">
<select ng-model="selectedId"
ng-options="id for id in availableSaleItemIds"
ng-change="updateSaleItemIds(saleItem, selectedId)">
<option value="">{{saleItem.id}}</option>
</select>
</tr>
AngularJS V1.4 included a major refactoring of the
ng-optionsdirective. The default option is now selected with a model value ofnull. For more information, see AngularJS Developer Guide - Migrating to V1.4 - ngOptions.When the user selects an option, the model is set to that new value and the
ng-changeupdates the available options. TheupdateSaleItemsIdsfunction removes that value from theavailableSaleItemIdslist. When the new list of options does not include the model value, theng-optionsdirective sets the model back tonulland invokes theng-changedirective again.The work around is to not update the list of options when the selected value is changed to
null.