Home > Net >  How to bind selected elements in SELECT multiple
How to bind selected elements in SELECT multiple

Time:10-19

I have a select multiple like this

<select
  id="countries"
  ng-model="country"
  ng-options="option.name for option in countryOptions track by option.id"
 multiple>
</select>

to populate this select I am doing:

let countries = [];
countries.push({
  id: country.id,
  name: country.name,
  selected: false
});
$scope.countryOptions = countries;

then acting on another element, I loop scope.countryOptions to check if any of its elements are in another array, and in that case I mark them as selected:

$scope.countryOptions.forEach((country, index) => {
  $scope.countryOptions[index].selected = activeCountries.indexOf(country.id) !== -1;
});

What should I do to have the selected elements highlighted in the select multiple (in the UI)?

CodePudding user response:

Your data source $scope.countryOptions and the user's selected countries $scope.country are different. Keep your data source pure and track user selections separately.

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.countryOptions  = [{ id: 1,  name: "Brazil" },
      { id: 2, name: "France" },
      { id: 3, name: "Djibouti" }
    ];
 
    let activeCountries = [1, 3]

    // init
    $scope.country = $scope.countryOptions.filter(c => activeCountries.indexOf(c.id) > -1)
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="selectExample">
  <div ng-controller="ExampleController">

    <select id="countries" ng-model="country" ng-options="option.name for option in countryOptions track by option.id" multiple>
    </select>
    <hr> {{country}}
  </div>
</div>

  • Related