javascriptangularjsclipboarddataonpasteng-paste

Ng-Paste - Accessing Pasted Data as an Array or List


The Idea

We're building an app in Angular 1.5.x and we're trying to implement a feature that would allow the user to paste a single column of cells from an excel sheet or any other spreadsheet (single column, any number of rows deep) into an input.

We've got a data table that contains inline inputs like the following: data table

The idea is that when they paste data copied from a single column of a spreadsheet into one of the inputs, the data would be parsed cell for cell and assigned to each input in descending order. I.E. If I pasted a column of cells containing [4.52, 6.235, 9.2301] into the top input containing 15.23, then 15.23 would become 4.52, 3.1234 would become 6.235, and 3.1322 would become 9.2301. We know how to assign the variables to the inputs, but we need the clipboardData in array format, not one big string.

The Problem

We've looked into doing this using the ng-paste directive and the $event.clipboardData property, but we only have access to the data as a string, and while we have a way of parsing the string, it would be much less error prone if we could access the elements coming in as an array or a list to prevent any errors on our end if we end up using delims to break up that string.

Here is a working plunker with what we're already trying.

Here is a sample data set to copy and paste into the input:

For some reason, when copying a column from an excel spreadsheet, it's got no delims between values. When we copy from multiple columns of a single row instead of multiple rows of a single column I'm able to .split() on the '\n' character and it works fine. It would be preferable to allow the user to copy both from across a single row and down a single column, however. The issue is just that there are no delims when you copy a column from excel.

0.89663.91783.91773.91773.9178

That is what pasted from an excel/google sheet^, but feel free to put those values in a single column of a spreadsheet and copy from there. We can be sure that the pasted data will be coming from a spreadsheet.

The Solution

Any ideas on how to grab that clipboard data as an array?


Solution

  • This should do the trick:

    HTML:

    <input ng-paste="pasteFunction($event)"><br />
    <p>Input as array:</p>
    <p ng-repeat="item in pasted track by $index">{{item}}</p>
    

    JavaScript:

      $scope.pasteFunction = function(ev) {
        $scope.pasted = ev.clipboardData.getData('text').split(" ").map(Number);
        console.log($scope.pasted);
      }
    

    Working Code: Plunker