Danny Mencos
Danny Mencos

Reputation: 1295

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?

Upvotes: 1

Views: 408

Answers (2)

David L
David L

Reputation: 33853

It is completely normal behavior.

ng-model is a separate binding from the options rendered by the backing array. As a result, changing the source of ng-options has no effect on the ng-model bound property.

If you are emptying your array, you need to also set myObject.selectedItem to null after setting the backing array length.

If you intend on doing this type of operation often and want it to dynamically update myObject.selectedItem, you could always register a watcher on myArrayList and set selectedItem to null if the length updates to 0.

Upvotes: 2

dror
dror

Reputation: 83

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.

Upvotes: 1

Related Questions