使用角度js从多选框中添加或删除所选元素

问题描述 投票:2回答:1

我想显示一个动态表,但我想在运行时选择表列。为此,我采用了两个多选框,在第一个Multi select中使用Json加载所有列名。

现在我的要求是,我想从第一个多选框到第二个多选框添加选定的列名。如果需要,我还想从第二个多选框中删除。

我有两个按钮,一个用于添加,另一个用于删除。任何人都可以帮我解决这个问题。我怎么能用AngularJs做到这一点?请参考附图清楚我的要求.enter image description here提前感谢..

angularjs angular-ui-bootstrap
1个回答
2
投票

angular.module('app', []).controller('MoveCtrl', function($scope) {

  $scope.available = [];
  $scope.selected = [];

  $scope.moveItem = function(items, from, to) {

    angular.forEach(items, function(item) {
      var idx = from.indexOf(item);
      from.splice(idx, 1);
      to.push(item);
    });

    // clear selection
    $scope.available = "";
    $scope.selected = "";
  };

  $scope.moveAll = function(from, to) {

    angular.forEach(from, function(item) {
      to.push(item);
    });
    from.length = 0;
  };

  $scope.selectedclients = [];
  $scope.availableclients = [{
    id: 1,
    name: 'Bob'
  }, {
    id: 2,
    name: 'Sarah'
  }, {
    id: 3,
    name: 'Wayne'
  }, {
    id: 4,
    name: 'Pam'
  }];

});
input {
  display: block;
  margin: 0 auto;
}
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="[email protected]" data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-controller="MoveCtrl">
  <h1>Move items between Select boxes</h1>

  <div style="float:left">
    <div>Available Clients</div>
    <div>
      <select size="5" multiple ng-model="available" ng-options="client as client.name for client in availableclients" style="width: 100px;height:100px"></select>
    </div>
  </div>
  <div style="float:left; width: 100px; text-align:center">
    <div>&nbsp;</div>
    <input id="moveright" type="button" value=">" ng-click="moveItem(available, availableclients,selectedclients)" />
    <input id="moverightall" type="button" value=">>" ng-click="moveAll(availableclients,selectedclients)" />
    <input id="move left" type="button" value="<" ng-click="moveItem(selected, selectedclients,availableclients)" />
    <input id="moveleftall" type="button" value="<<" ng-click="moveAll(selectedclients,availableclients)" />
  </div>

  <div style="float:left">
    <div>Selected Clients</div>
    <div>
      <select size="5" multiple ng-model="selected" ng-options="client as client.name for client in selectedclients" style="width: 100px;height:100px"></select>
    </div>
  </div>
  <div style="clear:both">
    <br/>
    <div>Selected Clients: {{selectedclients}}</div>
    <div>Available Clients: {{availableclients}}</div>
    <div>Selected: {{selected}}</div>
    <div>Available: {{available}}</div>
  </div>
</body>

</html>

归功于AngularJS moving items between two select list的基础。但是,只有在选择多个项目时才会移动单个项目。

© www.soinside.com 2019 - 2024. All rights reserved.