Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get clipboard data in angular JS

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

like image 745
Tasneem Hyder Avatar asked Jan 09 '14 18:01

Tasneem Hyder


2 Answers

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> 
like image 95
fyasir Avatar answered Oct 27 '22 01:10

fyasir


here's a concise version I use -

function copyToClipboard(data) {
    angular.element('<textarea/>')
        .css({ 'opacity' : '0', 'position' : 'fixed' })
        .text(data)
        .appendTo(angular.element($window.document.body))
        .select()
        .each(function() { document.execCommand('copy') })
        .remove();
}
like image 43
0cd Avatar answered Oct 27 '22 00:10

0cd