Skip to content

Instantly share code, notes, and snippets.

@JustMaier
Last active March 29, 2022 08:46
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save JustMaier/6ef7788709d675bd8230 to your computer and use it in GitHub Desktop.
Save JustMaier/6ef7788709d675bd8230 to your computer and use it in GitHub Desktop.
Simple copy to clipboard functionality in angular without any dependencies
<!-- View it live here: http://codepen.io/anon/pen/waZOjB -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/JustMaier/6ef7788709d675bd8230/raw/3d39d50e66d8d77e05656ed7dd09298be7e86f1f/ngClickCopy.js"></script>
<script>
angular.module('app', ['ngClickCopy'])
</script>
<div ng-app="app">
<button ng-click-copy="Hello World">Copy</button>
</div>
'use strict';
angular.module('ngClickCopy', [])
.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();
}
}])
.directive('ngClickCopy', ['ngCopy', function (ngCopy) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function (e) {
ngCopy(attrs.ngClickCopy);
});
}
}
}])
@ulrichdohou
Copy link

Thats you. It works perfectly for my case

@kennymuse
Copy link

With iOS device, there is a quick flick probably for the show/hide of the keyboard (probably for the focus) and don't copy the text.

@Zeioth
Copy link

Zeioth commented Jul 10, 2018

Simple and elegant, thanks!

@shashidhar7
Copy link

Thankyou. It works perfectly working

@NiranjanShah
Copy link

any ways to avoid clipboard copy paste in text area in mobile browsers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment