![](/img/trans.png)
[英]Cannot select default value in dropdown using ng-model and ng-repeat or ng-select in AngularJS
[英]AngularJS - Filter already selected items from ng-select inside ng-repeat
我發現了類似的問題,但沒有人遇到同樣的問題。 我有一個用戶可以添加的本地化列表(用於構建他們自己的UI本地化)。 它們可以為同一個項目提供多種語言,因此他們可以鍵入文本並從下拉列表中選擇相應的語言。
我只希望他們能夠選擇一次語言(他們在列表中使用兩種相同的語言是沒有意義的)。 這是HTML:
<div class="divider-header">
<h4>{{'contactAttributes.localization.title' | translate}}</h4>
<button id="add-label-btn" class="btn pull-right" title="Add a label"
ng-click="addLocalization()">
<i class="fa fa-plus center"></i>
</button>
</div>
<div ng-repeat="item in localizations track by $index">
<div class="input-group localization-group">
<label>{{'value.label' | translate}}</label>
<input type="text" ng-model="item.label">
<label>{{'value.language' | translate}}</label>
<select
required
ng-options="locale.value as locale.label for locale in localeNames | filter: alreadySelected"
ng-model="item.language"></select>
<i id="remove-localization-label"
class="fa fa-times remove"
ng-click="removeLocalization($index)"></i>
</div>
</div>
“alreadySelected”過濾器看起來像這樣(在指令中因此范圍而不是$ scope):
scope.alreadySelected = function(language) {
return !scope.localizations.filter(function(selectedValue) {
return selectedValue.language === language.value;
}).length;
};
scope.localizations包含已選擇的項目。 這幾乎可以工作,但它具有過濾掉從選擇框本身中選擇的選項的效果,因此當您選擇一個選項時,它會被過濾掉並且選擇框顯示為空白。 我需要該選擇框中的所選項目仍然顯示並且可以選擇,但僅限於該特定選擇框(而不是ng-repeat中的其他選項)。
如果這可以使用澄清,請告訴我。 謝謝!
編輯:這是一個顯示問題的傻瓜 - https://plnkr.co/edit/ALu00gitPg7GLfdGQ75a
所以我找到了一個解決方案,從lodash得到了一些幫助。 將ng-options更改為:
ng-options="locale.value as locale.label for locale in availableLocales($index)"
用這個替換alreadySelected函數:
scope.availableLocales = function(localizationIndex) {
return scope.localeNames.filter(function(locale) {
return !_.find(scope.localizations, function(localization, idx) {
if (localizationIndex === idx) return false;
return localization.language === locale.value;
});
});
};
如果有人有替代解決方案隨時分享,否則,謝謝你是我的橡皮鴨,StackOverflow。 :P
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.