我有一个<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'"