ng-change is fired a second time when selected option is removed from ng-options - AngularJS 1.7

1.5k views Asked by At

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>
1

There are 1 answers

3
georgeawg On BEST ANSWER

AngularJS V1.4 included a major refactoring of the ng-options directive. The default option is now selected with a model value of null. 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-change updates the available options. The updateSaleItemsIds function removes that value from the availableSaleItemIds list. When the new list of options does not include the model value, the ng-options directive sets the model back to null and invokes the ng-change directive again.

The work around is to not update the list of options when the selected value is changed to null.

<select ng-model="selectedId"
    ng-options="id for id in availableSaleItemIds"
    ̶n̶g̶-̶c̶h̶a̶n̶g̶e̶=̶"̶u̶p̶d̶a̶t̶e̶S̶a̶l̶e̶I̶t̶e̶m̶I̶d̶s̶(̶s̶a̶l̶e̶I̶t̶e̶m̶,̶ ̶s̶e̶l̶e̶c̶t̶e̶d̶I̶d̶)̶"̶
    ng-change="selectedId && updateSaleItemIds(saleItem, selectedId)">
    <option value="">{{saleItem.id}}</option>
</select>