AngularJS - Filter already selected items from ng-select inside ng-repeat

I found similar questions, but I don't have the same problem. I have a list of localizations that the user can add (to create their own localization of our user interface). They can have several languages ​​for the same element, so they can enter text and select the appropriate language from the drop-down list.

I just want them to be able to select a language once (it makes no sense for them to have two identical languages ​​on the list). Here is the 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>

The filter "already selected" looks like this (in the directive, and not in the scope):

scope.alreadySelected = function(language) {
  return !scope.localizations.filter(function(selectedValue) {
    return selectedValue.language === language.value;
  }).length;
};

scope.localizations . , , , , , , . , , ( ng-repeat).

, . !

EDIT: plunkr - https://plnkr.co/edit/ALu00gitPg7GLfdGQ75a

+4
1

, lodash. ng-options:

ng-options="locale.value as locale.label for locale in availableLocales($index)"

:

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

0

Source: https://habr.com/ru/post/1667681/


All Articles