在下拉菜单中显示先前选择的项目

Showing previously selected items in drop down menu

使用 angular 和 angular-xeditable 我有一个带有许多选项的下拉菜单,从中可以到 'amenities' 数组中的 select。

一旦我从下拉列表中保存了 selections 并保存了它们,我想让用户能够返回页面并编辑之前 selected 的项目。

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

有和这个一样的案例

添加 $scope.$watch 以将所选值放入 $scope.selectedValues,如下所示

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

然后像下面这样使用它:

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>  

完整代码位于 Plunker

希望对你有帮助。

你是这个意思吗?

var m = angular.module('m', []).controller('c', ['$scope',
  function($scope) {
    $scope.avilibleValues = ['a1', 'a2', 'a3', 'a4', 'a5'];
    $scope.selected = [];
    $scope.last = 'a1';
    $scope.selecting = 'a1';
    $scope.select = function(it) {
      console.log('select:' + it);
      $scope.selecting = it;
    };

    $scope.change = function() {
      console.log($scope.last);
      $scope.last && $scope.selected.push($scope.last);
      $scope.last = $scope.selecting;
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
<div ng-app="m">
  <div ng-controller="c">
    <div class="row">
      <label>seleted:</label>
      <div>
        <p ng-repeat="it in selected">
          <a ng-click="select(it)">{{it}}</a>
        </p>
        <div>

        </div>
        <div class="row">
          <label>selet</label>
          <select ng-model="selecting" ng-options=" i for i in avilibleValues" ng-change="change()"></select>
        </div>
      </div>
    </div>
    <p>
      selecting:{{selecting}}
      <p>
        selected:{{selected}}
        <p>
          last:{{last}}
          <p>

  </div>
</div>