How to copy string to clipboard using ng-click in AngularJS?

I want to copy the link to the click button in AnuglarJS. I tried the code below, but I am stuck with this error:

This is mine button:

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

this is 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();
    }

press the button. I want to copy this link so that someone can help me how to do this.

+4
source share
1 answer

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

Range.selectNode() , node . node , referenceNode.

, DOM, 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);
}

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

Source: https://habr.com/ru/post/1673703/


All Articles