hard coder
hard coder

Reputation: 5705

ng-model in select box is not working correctly

I am using angular js to draw select boxes.

 <select ng-model="selected">
     <option value="{{obj.id}}" ng-repeat="obj in values">{{obj.name}} </option>
 </select>
 selected id - {{selected}} 

Here the default selected is not initialized according to value selected.

Have made a fiddle for the problem.

Upvotes: 4

Views: 13968

Answers (4)

Saumyajit
Saumyajit

Reputation: 746

Correct Way would be like :

<select id="select-type-basic" [(ngModel)]="status">
    <option *ngFor="let status_item of status_values">
    {{status_item}}
    </option>
</select>

Value Should be avoided inside option since that will set the default value of the 'Select field'. Default Selection should be binded with [(ngModel)] and Options should be declared likewise.

status : any = "Completed";
status_values: any = ["In Progress", "Completed", "Closed"];

Declaration in .ts file

Upvotes: 0

Siew Wing Fei
Siew Wing Fei

Reputation: 21

Just add ng-selected="selected == obj.id" in the option tag

<option value="{{obj.id}}" ng-repeat="obj in values" ng-selected="selected == obj.id" > 
{{obj.name}} 
</option>

Upvotes: 1

Divya MV
Divya MV

Reputation: 2053

case 2 is updated in this plunker

http://jsfiddle.net/26yjn8ru/

 <div ng-repeat="arr in itr">
    <select ng-model="arr.id"
      ng-options="value.id  as value.name for value in values">
    </select>

Upvotes: 2

dfsq
dfsq

Reputation: 193251

You should use ngOptions directive to render selectbox options:

<select ng-model="selected" ng-options="obj.id as obj.name for obj in values"></select>

Fixed demo: http://jsfiddle.net/qWzTb/1984/

Upvotes: 8

Related Questions