Created
December 7, 2016 21:15
-
-
Save AntonisFK/0204e2a65f50c24d249c75d45fa3f5a1 to your computer and use it in GitHub Desktop.
angular directive to copy to clipboard
This file contains 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
(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