简体   繁体   English

从`中删除`array`中的元素 <select> `

[英]Remove elements in `array` from `<select>`

I have a <select> element which is rendered from an array with some vehicles in it. 我有一个<select>元素,它是从一个包含一些车辆的array呈现的。

When I choose a vehicle and add it to another array, I want it to not be displayed in the <select> element. 当我选择车辆并将其添加到另一个阵列时,我希望它不会显示在<select>元素中。 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. 对于那些喜欢这样的人来说,这是一个JSFiddle

How can I get rid of the added vehicles in the <select> element? 如何摆脱<select>元素中添加的车辆?

You also have to remove it from the original tags array, use Array#splice ( JSFiddle ): 您还必须将其从原始标记数组中删除,使用Array#spliceJSFiddle ):

$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 ): 要维护<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.

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