Yesterday I was requested to create a “copy to clipboard” behavior in an AngularJS application I’m building. The main idea was to mark some content which has a meaning and to enable the user to copy the “meaning” to the clipboard by pressing a button.
Here is the directive I ended up with:
The main idea is borrowed from a Stack Overflow answer – How does Trello access the user’s clipboard?
I use a invisible element container to wrap a textarea which will hold the content to copy. The directive model, textToCopy, is used to get the text that I copy which means that all the directive user needs to do is to hold in that model the text he wants to copy. Once the button is clicked, I put the textToCopy data in the textarea, call the textarea select function and use the document.execCommand(‘copy’) call to force the browser to copy the selected content.
Here is how you use the directive:
someText will be a property of the vm object which will hold the text you want to copy (in my application vm is a controller that is used with the controllerAs property).
I hope you’ll find this post useful.