如何在角度js表中启用多行选择

时间:2015-12-30 05:10:59

标签: angularjs

我创建了html表并使用ng-repeat来显示表中的项目, 但我不能在表格中选择多行。 如何通过使用控制键来实现这一点 谢谢!

let newArray = arr.group(item => item.optionName))

3 个答案:

答案 0 :(得分:8)

我希望这对你来说还不算太晚,我有你回答。

您可以使用 $ event.ctrlKey 参数来检查用户是否已按下控件。

更好的是,有一个 $ event.shiftKey 参数来检查是否按下了shift。

你可以这样使用它(我让一个简单的控制器中的所有逻辑,以便它更容易理解,但我建议你把它放在服务中)。 此外,我选择仅存储行索引,但它与完整行的工作方式相同。

<强> HTML

<tr ng-repeat="row in rows track by $index" ng-click="selectRow($event, $index)" ng-class="{highlitedRow: isRowSelected($index)}">

<强> AngularJS

var selectedRowsIndexes = [];
$scope.rows = [{name: 'Happy Butterfly'}, {name: 'Wonderful Bee'}];


$scope.selectRow = function(event, rowIndex) {
  if(event.ctrlKey) {
      changeSelectionStatus(rowIndex);
  } else if(event.shiftKey) {
      selectWithShift(rowIndex);
  } else {
      selectedRowsIndexes = [rowIndex];
  }
  console.log(selectedRowsIndexes);
  console.log(getSelectedRows());
  console.log(getFirstSelectedRow());
};

function selectWithShift(rowIndex) {
  var lastSelectedRowIndexInSelectedRowsList = selectedRowsIndexes.length - 1;
  var lastSelectedRowIndex = selectedRowsIndexes[lastSelectedRowIndexInSelectedRowsList];
  var selectFromIndex = Math.min(rowIndex, lastSelectedRowIndex);
  var selectToIndex = Math.max(rowIndex, lastSelectedRowIndex);
  selectRows(selectFromIndex, selectToIndex);
}

function getSelectedRows() {
  var selectedRows = [];
  angular.forEach(selectedRowsIndexes, function(rowIndex) {
    selectedRows.push($scope.rows[rowIndex]);
  });
  return selectedRows;
}

function getFirstSelectedRow() {
  var firstSelectedRowIndex = selectedRowsIndexes[0];
  return $scope.rows[firstSelectedRowIndex];
}

function selectRows(selectFromIndex, selectToIndex) {
  for(var rowToSelect = selectFromIndex; rowToSelect <= selectToIndex; rowToSelect++) {
    select(rowToSelect);
  }
}

function changeSelectionStatus(rowIndex) {
  if($scope.isRowSelected(rowIndex)) {
      unselect(rowIndex);
  } else {
      select(rowIndex);
  }
}

function select(rowIndex) {
  if(!$scope.isRowSelected(rowIndex)) {
      selectedRowsIndexes.push(rowIndex)
  }
}

function unselect(rowIndex) {
  var rowIndexInSelectedRowsList = selectedRowsIndexes.indexOf(rowIndex);
  var unselectOnlyOneRow = 1;
  selectedRowsIndexes.splice(rowIndexInSelectedRowsList, unselectOnlyOneRow);
}

function resetSelection() {
  selectedRowsIndexes = [];
}

$scope.isRowSelected = function(rowIndex) {
  return selectedRowsIndexes.indexOf(rowIndex) > -1;
};

});

最后,如果你想使用强大的表格,我建议你使用ng-table。

如果您使用ng-table,请务必添加

$scope.$on('ngTableAfterReloadData', function() {
  resetSelection();
});

并用 $ scope.tableParams.data [rowIndex]

替换$ scope.rows [rowIndex]

答案 1 :(得分:6)

在此示例中,我尝试检测选择了哪一行,因此我将selected param添加到已选择的每个对象中,然后我们可以使用$filter来检测所选行。

var app = angular.module("app", []);
app.controller("ctrl", function($scope, $filter) {
  $scope.users = [{
    name: "x"
  }, {
    name: "y"
  }, {
    name: "z"
  }];
  
  $scope.selectedRows = [];

  $scope.select = function(item) {
    item.selected ? item.selected = false : item.selected = true;
  }

  $scope.getAllSelectedRows = function() {
    var selectedRows = $filter("filter")($scope.users, {
      selected: true
    }, true);
    
    $scope.selectedRows = selectedRows;
  }

});
body {
  padding-top: 50px;
}

tr td {
  cursor: pointer
}

tr.selected td {
  background: #ccc!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="ctrl">
  <div class="container">
    <table class="table table-bordered">
      <tr ng-repeat="user in users" ng-class="{'selected': user.selected}" ng-click="select(user)">
        <td ng-bind="user.name" title="click to select a row"></td>
      </tr>
    </table>

    <button class="btn btn-primary" ng-click="getAllSelectedRows()">Get All Selected Rows</button>
    
    {{selectedRows | json}}
  </div>
</div>

答案 2 :(得分:0)

此演示使用Ctrl,Shift和两者的组合来对angularJs中的多个表行进行选择。 对于plnkr演示。

http://plnkr.co/edit/IGBCkLpmK4ecJ9RUsALa?p=preview

Html就像这样

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://code.angularjs.org/latest/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="multiSelectController as vm">
    {{vm.a}}
      <table>
      <thead>
      </thead>
      <tbody style="border:1px solid blue;">
        <tr ng-repeat="item in vm.externalProductsTypes" ng-click="vm.selectUnselectMultiple($index,$event)" ng-class="{'selected': vm.isRowSelectedUnselect($index)}">
          <td  style="border:1px solid blue;">{{item.id}}</td>
          <td  style="border:1px solid blue;">
            <div style="float:left;  margin-right: 10px;">{{item.name}}</div>
          </td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

控制器就像这样

var app = angular.module('app', []);

app.controller('multiSelectController', function() {
  var vm = this;
  /* Data loading */
  vm.externalProductsTypes = [{
    "id":1,
    "name": "Access Winback"
  }, {
    "id":2,
    "name": "ADSL",
  }, {
    "id":3,
    "name": "Bigpond ADSL Activation",
  }, {
    "id":4,
    "name": "Bigpond ADSL Recontracting",
  }, {
    "id":5,
    "name": "Bigpond Cable Activation",
  }, {
    "id":6,
    "name": "Bigpond Cable Recontracting",
  }, {
    "id":7,
    "name": "Bigpond VAS",
  }, {
    "id":8,
    "name": "Bigpond Wireless Activation",
  }, {
    "id":9,
    "name": "Bigpond Wireless Recontracting",
  }, {
    "id":10,
    "name": "Broadband Right Plan",
  }];
  /* click function */
  vm.selectUnselectMultiple = function (idx, event) {

            if (event.which != '1') {
                return;
            }

            var row = vm.externalProductsTypes[idx];
            row.rowIndex = idx;

            if (!event.ctrlKey && !event.shiftKey) {
                vm.clearAll();
                vm.toggleRow(row);
                vm.selectionPivot = row;
                return;
            }
            if (event.ctrlKey && event.shiftKey) {
                vm.selectRowsBetweenIndexes(vm.selectionPivot.rowIndex, row.rowIndex);
                return;
            }
            if (event.ctrlKey) {
                vm.toggleRow(row);
                vm.selectionPivot = row;
            }
            if (event.shiftKey) {

                vm.clearAll();
                vm.selectRowsBetweenIndexes(vm.selectionPivot.rowIndex, row.rowIndex);
            }
        }
        /* other supported functions */
        vm.toggleRow = function (row) {
            row.className = row.className == 's' ? '' : 's';
        }

        vm.selectRowsBetweenIndexes = function (ia, ib) {
            var bot = Math.min(ia, ib);
            var top = Math.max(ia, ib);

            for (var i = bot; i <= top; i++) {
                vm.externalProductsTypes[i].className = 's';
            }
        }

        vm.clearAll = function () {
            for (var i = 0; i < vm.externalProductsTypes.length; i++) {
                vm.externalProductsTypes[i].className = '';
            }
        }

        vm.isRowSelectedUnselect = function (index) {
            if (vm.externalProductsTypes[index].className=='s') { // if found, then select the row.
                return true;
            }
        }
});

最后用于行选择的CSS

.selected {
    background-color: steelblue !important;
    color: white;
    font-weight: bold;
}