-
-
Save ulrichdohou/5a5f2f31da4f4ff70dc0e892e805e22f 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); | |
}); | |
} | |
} | |
}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment