Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - setting selected value of dropdown does not work

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';
}
like image 559
OverMars Avatar asked Feb 04 '14 06:02

OverMars


2 Answers

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

$scope.ddlRooms = $scope.options[0].id;
like image 121
AlwaysALearner Avatar answered Nov 08 '22 12:11

AlwaysALearner


better to do:

<select ng-model="ddlRooms.id" ng-options="r.id as r.Name for r in Rooms">
like image 34
Will Sadler Avatar answered Nov 08 '22 11:11

Will Sadler