Skip to content

Instantly share code, notes, and snippets.

@AntonisFK
Created December 7, 2016 21:15
Show Gist options
  • Save AntonisFK/0204e2a65f50c24d249c75d45fa3f5a1 to your computer and use it in GitHub Desktop.
Save AntonisFK/0204e2a65f50c24d249c75d45fa3f5a1 to your computer and use it in GitHub Desktop.
angular directive to copy to clipboard
(function() {
.directive('copyToClipboard', function ($window) {
var body = angular.element($window.document.body);
var textarea = angular.element('<textarea/>');
textarea.css({
position: 'fixed',
opacity: '0'
});
function copy(toCopy, callback) {
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful) throw successful;
callback();
} catch (err) {
console.log("failed to copy", toCopy);
}
textarea.remove();
}
return {
restrict: 'E',
template: '<md-button>'+
'<md-icon>content_copy</md-icon>'+
'<md-tooltip md-direction="bottom">Copy to clipboard</md-tooltip>'+
'</md-button>',
link: function (scope, element, attrs) {
element.bind('click', function (e) {
copy(scope.copy, function(){
scope.success();
});
});
},
scope: {
success: '&',
copy: '@'
}
};
});
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment