MrBuggy MrBuggy - 5 months ago 8
HTML Question

Find item with specific ID and select it in dropdown

Hi I've got follow object:

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


I loop this object with ng-options in my select like this:

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


It shows me my items in my list, but the dropdown has the first time also a empty item and this is default. After I click on one of my items, the empty removes and my selected item is in the list. How can I search for the item with ID = -1 and select this as default in my list without the empty one? I tried it with this:

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


It finds my item, but how can I set it as default in my list?

Thanks and cheers.

SSH SSH
Answer

First add ng-model to select tag

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

and in controller

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