3

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?

http://jsfiddle.net/PqHsL/1/

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

1 Answer 1

4

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:

  1. 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]"

  2. 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>

Fiddle.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I used #2, but, yes, had to set the model explicitly first. thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.