Last active
March 29, 2022 08:46
-
-
Save JustMaier/6ef7788709d675bd8230 to your computer and use it in GitHub Desktop.
Simple copy to clipboard functionality in angular without any dependencies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
}); | |
} | |
} | |
}]) |
Thats you. It works perfectly for my case
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.
Simple and elegant, thanks!
Thankyou. It works perfectly working
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
@yourNameIsGood
To dynamically copy values you can use this directive as such
<h1 ng-click-copy="{{controllerAsName.property}}"> {{controllerAsName.property}}</h1>
so if you had your controller as say itemCtrl and you had a property name sku with a value of 987686755 then it would display the value inside the tag and when click would copy that value as well