25

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

user3799365
  • 1,087
  • 4
  • 17
  • 27
  • possible duplicate of [how to get clipboard data in angular JS](http://stackoverflow.com/questions/21028578/how-to-get-clipboard-data-in-angular-js) – cbass Mar 26 '15 at 06:47

7 Answers7

30

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.

Bishan
  • 15,211
  • 52
  • 164
  • 258
marmor
  • 27,641
  • 11
  • 107
  • 150
  • 1
    "how bad it is to manipulate DOM from a Controller" - Like most other "best practices" in Software Engineering imo, there are occassionally situations where it makes sense to break the best practice - I think this answer is great! – Jesus is Lord Jun 05 '18 at 18:35
  • ALWAYS! gives me [Object object] in the clipborad... [My Text is a JSON, but I modified the appendChild line to: copyElement.appendChild(document.createTextNode(JSONstringify(text_to_share))); So that shouldn't be the problem – Hobbamok Sep 20 '18 at 08:03
  • @Hobbamok comment out the last two lines (cleanup) and check your dev-console how that copyElement looks like and what does it contain – marmor Sep 20 '18 at 09:09
  • 1
    if you `createElement("pre")` instead of `span`, then you can copy/paste pretty-printed JSON (so that your pretty printed JSON doesn't get mangled into single line when assigned to text node within `span`). Tested in Chrome. – Dimitry K Sep 12 '19 at 15:59
  • or textarea instead of span – regeter Oct 21 '21 at 00:10
12

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>
byteC0de
  • 5,153
  • 5
  • 33
  • 66
10

if you don't want to add a new library to your project, and you create it by your self, here is a simple, easy solution:

note: I created it with promise functionality (which is awesome)

here is CopyToClipboard.js module file

angular.module('CopyToClipboard', [])
        .controller('CopyToClipboardController', function () {

        })
        .provider('$copyToClipboard', [function () {

            this.$get = ['$q', '$window', function ($q, $window) {
                var body = angular.element($window.document.body);
                var textarea = angular.element('<textarea/>');
                textarea.css({
                    position: 'fixed',
                    opacity: '0'
                });
                return {
                    copy: function (stringToCopy) {
                        var deferred = $q.defer();
                        deferred.notify("copying the text to clipboard");
                        textarea.val(stringToCopy);
                        body.append(textarea);
                        textarea[0].select();

                        try {
                            var successful = $window.document.execCommand('copy');
                            if (!successful) throw successful;
                            deferred.resolve(successful);
                        } catch (err) {
                            deferred.reject(err);
                            //window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
                        } finally {
                            textarea.remove();
                        }
                        return deferred.promise;
                    }
                };
            }];
        }]);

that's it, thanks to https://gist.github.com/JustMaier/6ef7788709d675bd8230

now let's use it

angular.module('somthing')
   .controller('somthingController', function ($scope, $copyToClipboard) {
       // you are free to do what you want
            $scope.copyHrefToClipboard = function() {
            $copyToClipboard.copy(/*string to be coppied*/$scope.shareLinkInfo.url).then(function () {
                //show some notification
            });
        };
   }

and finally the HTML

<i class="fa fa-clipboard" data-ng-click="copyHrefToClipboard($event)"></i>

hope this saves your time

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
4

You can use a module I made, ngClipboard. Here's the link https://github.com/nico-val/ngClipboard

You can use either ng-copyable directive, or the ngClipboard.toClipboard() factory.

Sampath
  • 63,341
  • 64
  • 307
  • 441
3

document.execCommand is now deprecated. Instead you can do:

HTML:

<i class="fa fa-copy" ng-click="copyToClipboard('some text to copy')"></i>

Controller:

$scope.copyToClipboard = function(string) {
    navigator.clipboard.writeText(string)
        .then(console.log('copied!'));          
}
fullstack
  • 754
  • 3
  • 20
2

In HTML:

<a href="#" ><img src="/Images/copy.png" ng-click="copyToClipboard("TEXT_YOU_WANTTO_COPY")"></img></a>

In Controller:

$scope.copyToClipboard = function (name) {
    var copyElement = document.createElement("textarea");
    copyElement.style.position = 'fixed';
    copyElement.style.opacity = '0';
    copyElement.textContent =  decodeURI(name);
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyElement);
    copyElement.select();
    document.execCommand('copy');
    body.removeChild(copyElement);
}
Kabiraj Kharel
  • 203
  • 2
  • 11
0

try this:

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

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

        try {
            var successful = document.execCommand('copy');
            if (!successful)
                throw successful;
           
        } catch (err) {
            window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
        }
        textarea.remove();
    }
}]);

You need to call this service to your controller. You can do like this:

controllers.MyController = ['$scope', 'ngCopy',
function ($scope, ngCopy) {
      ngCopy(copyText);
}];
Jayrag Pareek
  • 354
  • 3
  • 15