coderwill
coderwill

Reputation: 844

How to copy a string to clipboard with ng-click in AngularJS?

I want to copy link on click button in AnuglarJS. I have tried below code but I have stucked in this error:

This is my button :

<button class="btn btn-info" ng-click="test2(\'' + decodeURI(data.name) + '\');" >copy</button>

this my function in controller.js :

  $scope.test2 = function (name)
    {            
        var res = 'http://example.com?from=' + name;
        var range = document.createRange();         
        range.selectNode(res); // here getting error
        window.getSelection().addRange(range);
        try {                
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy email command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }     
        window.getSelection().removeAllRanges();
    }

click on button I want to copy this link any one can please help me how can do that.

Upvotes: 7

Views: 10354

Answers (1)

lin
lin

Reputation: 18392

According to the selectNode() documentation range.selectNode() expects a param of type node where your node is a string -> var res = 'http://example.com?from=' + name;.

The Range.selectNode() method sets the Range to contain the Node and its contents. The parent Node of the start and end of the Range will be the same as the parent of the referenceNode.

Just create a dummy element for copy, append it to your DOM, copy it and remove it from DOM:

$scope.copyToClipboard = function (name) {
    var copyElement = document.createElement("textarea");
    copyElement.style.position = 'fixed';
    copyElement.style.opacity = '0';
    copyElement.textContent = 'http://example.com?from=' + decodeURI(name);
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyElement);
    copyElement.select();
    document.execCommand('copy');
    body.removeChild(copyElement);
}

View

<button class="btn btn-info" 
        ng-click="copyToClipboard(data.name);">copy</button>

Upvotes: 17

Related Questions