user3116322
user3116322

Reputation:

Angular set model to null does not select empty option

http://plnkr.co/edit/JVMZqnY5Vilek4NxDNGE?p=preview

There is a select like this (nothing unusual here):

 <select ng-model="model.selectedValue"
         ng-options="value.id as value.value for value in modelOptions">
 <option value="" ng-if="!model.selectedValue">Null</option>

Initially the model is null, so when the page first opens the Null option is selected.

$scope.model ={"selectedValue":null};

However, if I then change the selected value to something else, and then back to null by clicking these two buttons

<button ng-click="model.selectedValue=1">Select Yes</button>
<button ng-click="model.selectedValue=null">Select Null</button>

then the Null option is NOT selected - so now the UI is out of sync with the model.

Clearly this is a bug with Angular (1.2.22), but is there any workaround?

Upvotes: 1

Views: 1578

Answers (2)

user3116322
user3116322

Reputation:

I have got an answer from the Angular team at https://github.com/angular/angular.js/issues/8670.

This was actually working up to version 1.2.14 but they don't think it's a bug. Apparently the right thing to do is not use the ng-if inside the select, and instead work with the model, the Javascript array of options the select is binding to.

I assume for the code sample in the question, this means setting up a watcher on model.selectedValue and adding/removing a Null option to/from modelOptions as appropriate.

Upvotes: 0

ms87
ms87

Reputation: 17492

Change the ng-if to ng-show:

<option value="" ng-show="!model.selectedValue">Null</option>

This is because ng-if creates a new scope, so you could also use ng-if along side $parent: <option value="" ng-if="!$parent.model.selectedValue">Null</option>

Upvotes: 2

Related Questions