Shaun Shaun - 1 year ago 51
HTML Question

ng-model with association on select box with ng-repeat on options

I have a Plunker here illustrating my issue. I have an object with an associated

. There is no
on the object, but in order to set or update the
I need to set the
field. Here's the sample object:

$scope.user = {
name: "John",
age: 32,
division: {
id: 3,
name: "Alpha"

And the example divisions:

$scope.divisions = [
name: "Gamma",
id: 1
name: "Alpha",
id: 3
name: "Beta",
id: 5

The way I'm building the select box is with
, which I was hoping would bypass the need to track ng-model for the selected value.

<div class="form-group">
<label for="">Division</label>
<select type="text" ng-model="user.division_id">
<option ng-repeat="division in divisions"
ng-selected=" ==">{{ }}</option>

As you can see in the demo, the
attribute is being placed on the right option, but still the select box display is blank. Even if I add
division_id: 3
to the object, it continues to be blank. How can I get this to work without having to do a conversion on the object when loading and updating?

Edit: To address this question being flagged as a duplicate, I think this is unique because I'm asking how to build the select box with
, not
. Though the answer is similar to the answer for the proposed duplicate, I think other people might get stuck on this method and find it helpful to see the answer requires a different technique.

Dan Dan
Answer Source

If you update your select as follows it will display by default to the users

<select ng-model="user.division" ng-options="d as for d in divisions track by">   

You seemed to be wanting to have a separate model division_id, the only reason I can think of for this is that you wanted to control the persistence of the user model when the selection is updated. If for some reason you want to intercept the end-users selection to the user model (or even just the in-memory user object) being updated then use a copy/there are many ways to do that, but it's not clear if that's what you're asking.

Updated plunkr

Note it would have worked to have kept the same option ng-repeat syntax, but this is the recommended angular way to deal with options.