2016-12-06 90 views
1

我使用ngRepeatngSelected<select>標籤時面臨的一個問題選擇項,這是代碼:<select>與ngRepeat不要當第一要素選擇

<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> 

此工作正常時,選擇的項目比其他第一個項目,但是當選擇的是第一位的,錯誤的輸出,而不是在HTML看起來不錯

<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

注:數字是值(而不是索引)

更新

現在我注意到,只有在選擇最後一個項具有ngSelected等於true,瀏覽器顯示細膩

這是成品保持單元數據:

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

更新2

plnkr與示例錯誤

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

+0

你可以包含你正在迭代的skus變量的數據嗎? – RickCoxDev

+0

[{「Key」:1,「Value」:「001」},{「Key」:2,「Value」:「002」}] – scumbag

+0

'y'對象初始化了嗎?你可能想要創建一個plnkr – bhantol

回答

1

使用ng-attr-value="s.Key"而不是value="{{s.Key}}"

嘗試plnkr

通知的差異僅僅是值:

<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> 

使用的表達評估時間{{}}和NG-重複編譯時間不同步爲一個可能認爲。這解釋了爲什麼只有最後一個被選中。

雖然根據official documentation - choosing between ng-options and ng-repeat你可以使用ng-repeat for ng選項,但在處理對象而不是id時,你可能會喜歡使用select as語法。還有其他性能方面的原因,爲什麼你可能想這樣做。

+0

此解決方案正常工作,我選擇它作爲answere,因爲此外解釋什麼是異想天開 – scumbag