Search code examples
htmlangularjsdrop-down-menux-editable

Showing previously selected items in drop down menu


Using angular and angular-xeditable I have a drop down menu with a number of options from which to select in the 'amenities' array.

Once I save the selections from the drop down and saved them, I want to make it possible for the user to come back to the page and edit previously selected items.

HTML:

<select multiple  class="w-select am-dropdown" size="12" data-ng-model="Amenities" 
data-ng-options="amenity.amenity for amenity in amenities" required=""></select>

JS:

$scope.amenities = [{amenity: coffee}, {amenity: beer}, {amenity: parking}];

$scope.Amenities = [];

$scope.selectedAmenities = [coffee, beer];//these are amenities saved in the 
database that I want to be able to show as selected using the editable form

Solution

  • Have a case as same as this

    Add $scope.$watch to put selected value to $scope.selectedValues as below

    $scope.$watch('selectedAmenities ', function (nowSelected) {  
       $scope.selectedValues = [];  
       if (!nowSelected) {  
         return;  
       }  
       angular.forEach(nowSelected, function (val) {  
         $scope.selectedValues.push(val.amenity.toString());  
       });  
     }); 
    

    And then use it like below:

    select multiple ng-model="selectedValues" class="w-select am-dropdown" size="12"  >  
       <option ng-repeat="amenity in amenities" value="{{amenity.amenity}}" ng-selected="{{selectedValues.indexOf(amenity.amenity)!=-1}}">{{amenity.amenity}}</option>  
     </select>  
    

    Full code at Plunker

    Hope it helps you.