Search code examples
javascriptangularjsangularjs-ng-modelangularjs-ng-options

ng-options bound variable is not updated after clearing the array


I'm using an array to populate a list with ng-options, and a property binded to the selected item. After clearing the array, the bound variable myObject.selectedItem keeps the value of the last item selected.

HTML:

<select ng-model="myObject.selectedItem" ng-options="item.Id as item.Name for item in myArrayList | orderBy:'Id'" required>
    <option value="">Select something</option>
</select>

JS:

$scope.myArrayList = [ { Id: 1, Name: "Item 1" }, { Id: 2, Name: "Item 2" } ];
$scope.myObject = { selectedItem: null };

... after selecting Item 2:

$scope.myArrayList.length = 0;              // Clears the array
console.log($scope.myObject.selectedItem);  // Prints: 2

Is this a normal behavior?


Solution

  • The value stored in ... .selectedItem is saved, and is not bound to where the original value came from.

    So yes, this is the normal and expected behaviour.