7

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.

1 Answer 1

17

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>
Sign up to request clarification or add additional context in comments.

9 Comments

but here in my question how can do that please tell me.
range.selectNode() using this is not possible?
It's simply not needed.
but i am copy this link in the table data so i want to just click on button pass name and i have add link+name and pass res = "string" i want to like this. i am not used any text area,etc..
Yea, thats what you can do with this solution. Looks like you don't understand it. Added the view, hopefully you understand it now.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.