sonicblis sonicblis - 1 year ago 86
AngularJS Question

Setting selected values for ng-options bound select elements

Fiddle with the relevant code:

I'm trying to set the selected value of a drop down that is bound to a child collection of an object referenced in an ng-repeat. I don't know how to set the selected option since I can't reference the collection it's being bound to in any way that I'm aware of.


<div ng-app="myApp" ng-controller="SomeController">
<div ng-repeat="Person in People">
<div class="listheader">{{Person.firstName}} {{Person.lastName}}</div>
<div class="listitem" ng-repeat="Choice in Person.Choices">
ng-options="choice.Name for choice in Choice.Options"></select>


var myApp = angular.module('myApp', []);
myApp.controller("SomeController", function($scope) {
$scope.People = [{
"firstName": "John",
"lastName": "Doe",
"Choices": [
"Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
"SelectedOption":{Name:"Chicken",ID:2} //this doesn't work
"Options":[{Name:"Macaroni",ID:1}, {Name:"PB&J",ID:2}, {Name:"Fish",ID:3}],
}, {
"firstName": "Jane",
"lastName": "Doe"

Is this the one case where I should actually be using ng-init with a SelectedIndex on the model?

Answer Source

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

    ng-options="choice.Name for choice in Choice.Options track by choice.ID">

Updated fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download