AngularJS - setting selected value of dropdown does not work

偶尔善良 提交于 2019-12-09 10:32:37

问题


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';
}

回答1:


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

$scope.ddlRooms = $scope.options[0].id;



回答2:


better to do:

<select ng-model="ddlRooms.id" ng-options="r.id as r.Name for r in Rooms">


来源:https://stackoverflow.com/questions/21545850/angularjs-setting-selected-value-of-dropdown-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!