AngularJS:如何将选定的 table 行复制到剪贴板?

AngularJS: how to copy selected table rows to clipboard?

我创建了一个 table,其中包含 select 行复选框的选项,效果很好。

现在我正在寻找一些东西 - 想法、示例、类似案例 - 来帮助我将那些 selected 行复制到剪贴板,然后将它们粘贴到 Excel 文件中。

我可以在控制器中通过 checked 属性 或通过 AngularJS 的 filter 功能过滤所有项目列表。

我的table:

<button ng-click="copySelected()" type="button">Copy selected to clipboard</button>

<table>
<thead>
    <tr>
        <th><input type="checkbox" ng-model="selectAll" ng-change="toggleAll()"></th>
        <th>ID</th>
        <th>Date</th>
        <th>Subject</th>
    </tr>
</thead>
<tbody ng-repeat="item in items">
    <tr>
        <td><input type="checkbox" id="chk-{{item.id}}" ng-model="options[$index]" ng-value="item.id" 
                ng-change="toggleItem($index)"></td>
        <td>{{item.id}}</td>
        <td>{{item.issueDate}}</td>
        <td>{{item.subject}}</td>
    </tr>
</tbody>
</table>

AngularJS 控制器:

$scope.selectAll = false;
$scope.options = [];


$scope.toggleItem = function(index) {
   $scope.items[index].checked = !$scope.items[index].checked;
   if (!$scope.items[index].checked) {
      $scope.selectAll = false;
   }
};
  
$scope.toggleAll = function() {
   var checked = $scope.selectAll;
   for (var i = 0; i < $scope.items.length; i++) {
     $scope.options[i] = checked;
     $scope.items[i].checked = checked;
   }
};

// this is where I don't know how to progress from
$scope.copySelected = function() {
    
    if ($scope.selectAll) {
        
    } else {
        for (var i = 0; i < $scope.items.length; i++) {
            if ($scope.items[i].checked) {
                

            }
        }
    }
};

一种可能性是将所选项目数组转换为 CSV format. Then you can use the browsers clipboard api 以将 csv 有效负载写入剪贴板。

当我在 Libreoffice 中执行此操作时 - 在复制和粘贴到工作簿时,应用程序会提示我导入文本格式。在 Excel 中,这可能需要一些调整,甚至需要用户格式化数据。

  • 您也可以使用 SheetJs 生成一个 Excel 文件 - 但对于您的用例来说可能会显得臃肿。
  • 您可以将生成的 CSV 直接发送到浏览器。

剪贴板 api 在 IE 中不可用。