0

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.

webta.st.ic
  • 4,781
  • 6
  • 48
  • 98
  • 1
    You should assign first option to ng-model (which is missing from your code btw) of your select. see http://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select – Keammoort Jun 20 '16 at 08:17
  • @Keammoort Thanks, look at the answer, which is marked as correct. I edited it. With ng-model and find(), I can set it now as default, no matter if it's the first index or last. Cheers – webta.st.ic Jun 20 '16 at 08:38

2 Answers2

1

Init your select's model to the first item in the array:

<select ng-init="selectedItem = myList.Items[0]" 
        ng-model="selectedItem" 
        ng-options="option as option.Name for option in myList.Items">
</select>
iuliu.net
  • 6,666
  • 6
  • 46
  • 69
1

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);
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98
Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • Hi and thanks, I edited you're code a little bit: I need a solution for select the item with ID == -1 in every case, also when it's not at the first index in the list -> so I added the ng-model (you were right with this) and add him the item with ID == -1, which I find in the list with find(). Thanks and cheers.. – webta.st.ic Jun 20 '16 at 08:37