简体   繁体   中英

Remove elements in `array` from `<select>`

I have a <select> element which is rendered from an array with some vehicles in it.

When I choose a vehicle and add it to another array, I want it to not be displayed in the <select> element. However, I cannot figure out how to achieve this.

Here is my current code:

 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> 

And a JSFiddle for those of you who prefers that.

How can I get rid of the added vehicles in the <select> element?

You also have to remove it from the original tags array, use 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);
  }
}

To maintain the order of the <option> s, you can order the elements by id ( JSFiddle ):

ng-options="tag.name group by tag.type for tag in tags | orderBy:'+id'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM