在下拉列表中查找具有特定 ID 和 select 的项目

Find item with specific ID and select it in dropdown

嗨,我有关注对象:

        myList = {
            Items: [
                {
                    ID: -1,
                    Name: "Default item"
                },
                {
                    ID: 0,
                    Name: "Some item"
                },
                {
                    ID: 12,
                    Name: "Item 1"
                }
            ]
        };

我在 select 中使用 ng-options 循环此对象,如下所示:

<select ng-options="option as option.Name for option in myList.Items"></select>

它显示了我的列表中的项目,但下拉列表第一次也有一个空项目,这是默认设置。单击我的其中一项后,空的将被删除,我的 selected 项目将出现在列表中。我如何在我的列表中搜索 ID = -1 和 select 的默认项目而不是空项目?我试过这个:

let myDefault = myList.Items.find((item:any) => item.ID == -1);

它找到了我的项目,但如何将其设置为我列表中的默认项?

感谢和欢呼。

将您的 select 模型初始化为数组中的第一项:

<select ng-init="selectedItem = myList.Items[0]" 
        ng-model="selectedItem" 
        ng-options="option as option.Name for option in myList.Items">
</select>

首先将ng-model添加到select标签

 <select ng-model="select" 
         ng-options="option as option.Name for option in myList.Items">
 </select>

并在控制器中

 $scope.select = $scope.myList.Items.find((item:any) => item.ID == -1);