3

I got some problems with selectbox.

In my original code, I receive an object through $http calling, and that is like below.

[
    {key:'user_id', value:'ID'},
    {key:'user_name', value:'Name'},
    {key:'user_gender', value:'Gender'},
    {key:'user_phone', value:'Phone'},
    {key:'user_email', value:'Email'},
    {key:'user_birth', value:'Birthday'},
];

When I tried to put values of this object into option, it made 'blank option' automatically.

To solve this, I saw two posts

Angular JS Remove Blank option from Select Option

Why does AngularJS include an empty option in select?

but any solutions of these could not help me.

How can I fix this?

Here's my fiddle.

Select box create blank option

I'll wait some handsome or pretty developers who will solve my problem. :)

Canet Robern
  • 1,049
  • 2
  • 11
  • 28

2 Answers2

4

Try This

HTML Code -

<select ng-options="opt as opt.value for opt in searchOpt.option" ng-model="searchOpt.selected">
    </select>

The ngOptions attribute can be used to dynamically generate a list of elements for the element using the array or object obtained by evaluating the ngOptions comprehension expression

Working Jsfiddle

Manoj Patidar
  • 1,171
  • 2
  • 11
  • 29
  • oh my... you just saved someone's life.. thanks! But I got a question. Now, select box default value is last value of option. I want to set first value to default. can you fix this too? – Canet Robern Sep 21 '17 at 04:27
  • 1
    Please go through this link will resolved your issue https://docs.angularjs.org/api/ng/directive/ngOptions – Manoj Patidar Sep 21 '17 at 04:52
  • 1
    @CanetRobern : I've update the Ans. please look into this. hope this will resolve your issue https://jsfiddle.net/3pp61gny/9/ – Manoj Patidar Sep 21 '17 at 05:06
  • I don't know why your fiddle works fantastic, but not mine.. T.T – Canet Robern Sep 21 '17 at 05:23
3
<select ng-model="itemSelected">
  <option
      ng-repeat="item in data" value="{{ item.key }}"
      ng-selected="{{item.key === itemSelected}}">
    {{ item.value }}
  </option>
</select>

https://plnkr.co/edit/QthDhkvku8UvcVHaWcGG?p=preview

Check the code. Use ng-selected in your option for selected first element.

Mahfuz Shishir
  • 841
  • 1
  • 7
  • 24
  • thanks to your suggestion, but I think my problem has occurred by using `$q`. If put `$q` into your code, maybe same problem will occur. – Canet Robern Sep 21 '17 at 04:07