AngularJS - setting selected value of dropdown does not work
Asked Answered
R

2

8

I made a fiddle replicating my problem here: http://jsfiddle.net/U3pVM/2840/

As the title suggests, I can't set the selected value of a select populated using ng-options.

I have searched and tried all possible solutions that I found. Any help or suggestions would be appreciated!

HTML

<div ng-app>
    <h2>Todo</h2>
    <div ng-controller="TodoCtrl">
        <select ng-model="ddlRooms" ng-options="r.id as r.Name for r in Rooms">
        </select>
        {{$scope.test}}
    </div>
</div>

Angular

function TodoCtrl($scope) {
    $scope.Rooms = [{ Name: 'Toddler', id: 1 },{ Name: 'other', id: 2 }];
    $scope.options = [{ Name: 'other', id: 2 }];
    $scope.ddlRooms = $scope.options[0];

    $scope.test = 'bla';
}
Remunerate answered 4/2, 2014 at 6:54 Comment(0)
T
16

Because you are doing id as name you need to assign id to the model:

$scope.ddlRooms = $scope.options[0].id;
Toneytong answered 4/2, 2014 at 7:0 Comment(2)
That did it! Thank you very much! Any insights as to why? I'm assuming its because Angular binds to the value..Remunerate
How to solve it if my select tag is like: <select ng-model="formA.ddlRooms" ng-options="r.id as r.Name for r in Rooms">Atrocity
D
6

better to do:

<select ng-model="ddlRooms.id" ng-options="r.id as r.Name for r in Rooms">
Dietetics answered 19/8, 2015 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.