Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs how to set the default value for select

I have the following object:

defaults = {
0 : {
    id : 10,
    value : "string 1"
    },
1 : {
    id : 22,
    value : "string 2"
    }
}

I want to iterate over this object and display it as a select box.

<select ng-model="selectedValue" ng-options="obj.id as obj.value for obj in defaults">
   <option value="">---Select option-----</option>
</select>

What I'm trying to achieve is to select 'string 2' by default. But it does not work. The problem I have is the fact the selectedValue is a string:

$scope.selectedValue = "string 2";

From what I learned from the documentation the selectedValue must be the same object. But unfortunately, it is not possible. In my case selectedValue must be a string. In other words I need to operate with the name of the option only, I don't care about id. I tried to use ng-repeat. It even works but displays an empty option and I don't think using ng-repeat is a good way to do it.

Any advice will be appreciated greatly.

like image 652
Sray Avatar asked Dec 20 '25 12:12

Sray


1 Answers

If you want the selectedValue variable to contain the value, and not the ID, then you should not use obj.id as obj.value, but obj.value as obj.value.

like image 190
JB Nizet Avatar answered Dec 23 '25 04:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!