Reputation: 181
When using the angular directive ng-selected on an option, the bound model doesn't get updated until you manually change the selection. Is this as designed?
<div ng-app ng-init="colors=['red', 'yellow', 'blue']">
<select ng-model=selectedElement>
<option ng-repeat="color in colors" value="{{color}}" ng-selected="$last">{{color}}</option>
</select>
selectedElement: {{ selectedElement }}
</div>
Upvotes: 3
Views: 6234
Reputation: 364697
I don't know if it is working as designed.
I get the impression that ng-selected and ng-model don't play well together. (Note that the ng-selected API page doesn't use ng-model in the example select list.)
Here are two ways to workaround this:
set the bound model in addition to setting ng-selected. ng-init can also be used for this:
ng-init="colors=['red', 'yellow', 'blue']; selectedElement=colors[colors.length-1]"
set the bound model, don't use ng-selected, use ng-options:
...ng-init as above...
<select ng-model=selectedElement ng-options="color for color in colors">{{color}}</select>
Solution 1 has that weird "blank"/empty option, which disappears when you select something. Solution 2 doesn't have the empty option, and is less verbose. (So yeah, I like solution 2.)
I'm not sure what the use case is for ng-selected if we can set the model to preselect an option. We can change the selection programatically later also -- see the ng-click in the Fiddle.
Upvotes: 4