AngularJS - 设置下拉列表的选定值不起作用

时间:2021-02-13 15:06:06

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

我在这里复制了我的问题小提琴:http://jsfiddle.net/U3pVM/2840/

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

正如标题所示,我无法设置使用ng-options填充的选择的选定值。

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

我搜索并尝试了所有可能的解决方案。任何帮助或建议将不胜感激!

HTML

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

2 个解决方案

#1


16  

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

因为您正在使用id作为名称,所以需要为模型分配id:

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

#2


6  

better to do:

更好:

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

#1


16  

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

因为您正在使用id作为名称,所以需要为模型分配id:

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

#2


6  

better to do:

更好:

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