how to get clipboard data in angular JS

Tasneem Hyder picture Tasneem Hyder · Jan 9, 2014 · Viewed 35.9k times · Source

I was actually looking to get the content of clipboard using angular JS to simulate a copy paste thing.

Answer

fyasir picture fyasir · Feb 4, 2016

I created a directive for copy to clipboard which is using the document.execCommand() method.

Directive

(function() {
app.directive('copyToClipboard',  function ($window) {
        var body = angular.element($window.document.body);
        var textarea = angular.element('<textarea/>');
        textarea.css({
            position: 'fixed',
            opacity: '0'
        });

        function copy(toCopy) {
            textarea.val(toCopy);
            body.append(textarea);
            textarea[0].select();

            try {
                var successful = document.execCommand('copy');
                if (!successful) throw successful;
            } catch (err) {
                console.log("failed to copy", toCopy);
            }
            textarea.remove();
        }

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind('click', function (e) {
                    copy(attrs.copyToClipboard);
                });
            }
        }
    })
}).call(this);    

Html

<button  copy-to-clipboard="Copy Me!!!!" class="button">COPY</button>