首页 > 解决方案 > 显示从列表中的下拉列表中选择的多个值

问题描述

我有一个 angularjs 函数,其中包含一个值数组,如下所示

$scope.arrayVal = function()
{
var array = [{id:1,name:"one"},{id:2,name:"two"}];
}

我将此数组传递给我在 html 页面中的下拉列表,并在下拉列表中显示值,如下所示

<html>

<select ng-model="data.selected">
<option value="item.id,item.name" ng-repeat="item in array">{{item.id}} {{item.name}}</option>
</html>

我想要实现的是我想让用户从下拉列表中选择多个值,并且这些选择的值应该根据下拉列表下方的选择顺序显示。如何仅使用 angularjs 和 html 来实现这一点。(我没有使用除 angularjs 之外的任何库)

标签: htmlangularjshtml-select

解决方案


试试这个插件https://next.plnkr.co/edit/6Nxaxz9hGNXospyT。你可能不得不修改它以获得你想要的结果

<div ng-controller="ctrl">
    <select ng-model="selectedItem" ng-options="item.name for item in items" ng-change="selectItem()">
    </select>
    <p ng-repeat="item in selectedItems">{{item.id}} - {{item.name}}</p>
</div>
angular.module('app', [])

.controller('ctrl', function($scope) {
  $scope.items = [{id:1,name:"one"},{id:2,name:"two"}];
  $scope.selectedItems = [];
  $scope.selectedItem;

  $scope.selectItem = function () {
    var index = $scope.selectedItems.findIndex(function (fItem) { return $scope.selectedItem.id === fItem.id; });
    console.log(index)
    if (index > -1) $scope.selectedItems.splice(index, 1);
    else $scope.selectedItems.push($scope.selectedItem);
  };
});

推荐阅读