Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS copy to clipboard

Is there a way to make a copy button with a copy function that will copy all the contents of a modal and you can paste it to notepad

like image 555
user3799365 Avatar asked Mar 25 '15 22:03

user3799365


2 Answers

I needed this functionality in my Controller, as the text to be copied is dynamic, here's my simple function based on the code in the ngClipboard module:

function share() {
    var text_to_share = "hello world";

    // create temp element
    var copyElement = document.createElement("span");
    copyElement.appendChild(document.createTextNode(text_to_share));
    copyElement.id = 'tempCopyToClipboard';
    angular.element(document.body.append(copyElement));

    // select the text
    var range = document.createRange();
    range.selectNode(copyElement);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    // copy & cleanup
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    copyElement.remove();
}

P.S.
You're welcome to add a comment now telling me how bad it is to manipulate DOM from a Controller.

like image 122
marmor Avatar answered Nov 12 '22 20:11

marmor


If you have jquery support use this directive

.directive('copyToClipboard', function () {
        return {
            restrict: 'A',
            link: function (scope, elem, attrs) {
                elem.click(function () {
                    if (attrs.copyToClipboard) {
                        var $temp_input = $("<input>");
                        $("body").append($temp_input);
                        $temp_input.val(attrs.copyToClipboard).select();
                        document.execCommand("copy");
                        $temp_input.remove();
                    }
                });
            }
        };
    });

Html

<a href="" copy-to-clipboard="Text to copy">Copy text</a>
like image 12
byteC0de Avatar answered Nov 12 '22 19:11

byteC0de