I had to implement a copy to clipboard functionality for our Control Panel which lists Orders.
Since I’m a total enemy of flash I pursued a solution suitable for my needs and here it is.
This is based on http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript but I removed most of the styling and simply put the textarea outside of the viewport.
>> The Code!!
First create the helper function in your controller (this can be move to a helper service as well if you wan’t)
$scope.CopyTextToClipboard = function(text) { var TextAreaElement = document.createElement("textarea"); // Place in outside of the visible area of the screen regardless of scroll position. TextAreaElement.style.position = 'absolute'; TextAreaElement.style.top = -100; TextAreaElement.style.left = 0; // add text to the textbox TextAreaElement.value = text; // append TextAreaElement to document document.body.appendChild(TextAreaElement); // select the content TextAreaElement.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; $log.info('Copying text "' + text + '" to clipboard was ' + msg); } catch (err) { $log.error('Cannot copy to clipboard'); } // remove the TextAreaElement from the document document.body.removeChild(TextAreaElement); // unload TextAreaElement = undefined; }
And now simply bind it to your Element like this
<div ng-click="CopyTextToClipboard('My Text to copy');"></div>
This solution currently supports the following browsers.
Desktop:
- IE 9+
- Firefox 41+ (below that you have to enable copy in the user.js but since it’s enabled by default in the next Stable I don’t really care)
- Chrome 42+
- Opera 29+
- Safari has no support for this sadly 🙁
Mobile:
- Chrome for Android 42+
- Firefox Mobile 41+
I’m quite happy with this and maybe someone will find this useful.