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.
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);
}
<button class="btn btn-info"
ng-click="copyToClipboard(data.name);">copy</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With