[英]Remove elements in `array` from `<select>`
我有一個<select>
元素,它是從一個包含一些車輛的array
呈現的。
當我選擇車輛並將其添加到另一個陣列時,我希望它不會顯示在<select>
元素中。 但是,我無法弄清楚如何實現這一目標。
這是我目前的代碼:
var app = angular.module('app', []); function MyCtrl($scope) { $scope.chosenTags = []; $scope.tags = [ { id: 1, name: 'Ford', type: 'Car' }, { id: 2, name: 'Open', type: 'Car' }, { id: 3, name: 'Ferrari', type: 'Car' }, { id: 4, name: 'Mountain', type: 'Bike' }, { id: 5, name: 'BMX', type: 'Bike' }, { id: 6, name: 'Racing', type: 'Bike' }, ]; $scope.currentTag = $scope.tags[0]; $scope.addTag = function() { $scope.chosenTags.push($scope.currentTag); } }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="MyCtrl"> <select ng-model="currentTag" id="tags" ng-options="tag.name group by tag.type for tag in tags"></select> <button ng-click="addTag()">Add</button> <hr /> <div ng-repeat="tag in chosenTags">{{ tag }}</div> </div> </div>
對於那些喜歡這樣的人來說,這是一個JSFiddle 。
如何擺脫<select>
元素中添加的車輛?
您還必須將其從原始標記數組中刪除,使用Array#splice ( JSFiddle ):
$scope.addTag = function() {
var idx = $scope.tags.indexOf($scope.currentTag);
if(idx >= 0) {
$scope.chosenTags.push($scope.currentTag);
$scope.tags.splice(idx, 1);
}
}
要維護<option>
的順序,可以按id( JSFiddle )對元素進行排序 :
ng-options="tag.name group by tag.type for tag in tags | orderBy:'+id'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.