scmbgx
scmbgx

Reputation: 81

<select> with ngRepeat dont select item when first element selected

I'm facing a problem when using ngRepeat and ngSelected inside <select> tag, this is the code:

<select ng-model="y.SkuId" ng-change="y.Edited=true;">
    <option ng-repeat="s in skus" ng-selected="s.Key == y.SkuId" value="{{s.Key}}">{{s.Value}}
    </option>
</select>

This works fine when the selected item is other than the first item, but when the selected is the first one, outputs wrong, instead that the html looks good

<option ng-repeat="s in skus" ng-selected="s.Key == y.SkuId" 
value="1" class="ng-binding ng-scope" selected="selected">001 

Output image in explorer

Note: the numbers are the values (not the index)

Update

Now I noticed that only when the last one item in options has the ngSelected equals true, browsers displays fine

This is the skus data:

[{ "Key" : 1, "Value" : "001" }, { "Key" : 2, "Value" : "002" }]

Update 2

plnkr with example of error

http://plnkr.co/edit/g8hRHzt1k54ingQdMHHY?p=preview

Upvotes: 1

Views: 1487

Answers (2)

bhantol
bhantol

Reputation: 9616

Use ng-attr-value="s.Key" instead of value="{{s.Key}}".

Try plnkr

Notice the difference is just the value:

<select ng-model="k.Key" >
  <option ng-repeat="s in skus" ng-selected="s.Key === k.Key" 
     ng-attr-value="s.Key">{{s.Value}}</option>
</select>

The expression evaluation time using {{}} and the ng-repeat compile time are not in sync as one may think. This explain why only the last was selected.

While according to official documentation - choosing between ng-options and ng-repeat you can use ng-repeat for ng-options but in the cases when you are dealing with objects instead of Ids you may like to use select as syntax. Also there are other performance reasons why you may want to do so.

Upvotes: 1

Andriy
Andriy

Reputation: 15442

try to use ngOptions within select element instead of ngRepeat directive:

<select ng-model="d.SkuId"
        ng-options="s.Key as s.Value for s in skus">
</select>

plunker: http://plnkr.co/edit/TQIxqSv9ZBleLeA2h6WQ?p=preview

Upvotes: 2

Related Questions