[英]Remove elements in `array` from `<select>`
我有一个<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'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.