I have a Plunker here illustrating my issue. I have an object with an associated division
. There is no division_id
on the object, but in order to set or update the division
I need to set the division_id
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 ng-repeat
, 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="user.division.id == division.id">{{ division.name }}</option>
</select>
</div>
As you can see in the demo, the selected
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 ng-repeat
, not ng-options
. 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.