2015-10-15 101 views
0

使用角度和角度可調整我有一個下拉菜單,其中有許多選項可以在'amenities'數組中選擇。顯示之前在下拉菜單中選擇的項目

一旦我從下拉列表中選擇並保存它們,我想讓用戶可以回到頁面並編輯以前選擇的項目。

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 

回答

1

具有與此相同

添加$範圍的情況下,$看把選擇的價值$ 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

希望它可以幫助你。

+0

感謝您的回答。它像一個魅力。我不完全理解它;你擺脫了Amenities陣列,但你的解決方案並不需要它。在選擇一件商品之前,事情有點奇怪,但它符合規範。謝謝。 – rashadb

+0

歡迎您! –

1

你是不是說這個?

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>