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

时间:2014-11-15 17:38:39

标签: javascript html angularjs

我有一个<select>元素,该元素由array呈现,其中包含一些车辆。

当我选择车辆并将其添加到另一个阵列时,我希望 not 显示在<select>元素中。但是,我无法弄清楚如何实现这一目标。

这是我目前的代码:

&#13;
&#13;
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);
	}
}
&#13;
<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>
&#13;
&#13;
&#13;

对于那些喜欢这种情况的人来说,JSFiddle

如何摆脱<select>元素中添加的车辆?

1 个答案:

答案 0 :(得分:3)

您还必须将其从原始代码数组中删除,使用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);
  }
}

要维持<option>的顺序,您可以按ID(JSFiddle)订购元素:

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