1

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?

1 Answer 1

3

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'"
Sign up to request clarification or add additional context in comments.

3 Comments

JSFiddle please . . .
I did think of this, but the problem is that when you put it back again, it's in another order than it was initially. I made your changes to this fiddle: jsfiddle.net/HB7LU/8347
@Maeh you can always order it like so: ng-options="tag.name group by tag.type for tag in tags | orderBy:'+id'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.