I was actually looking to get the content of clipboard using angular JS to simulate a copy paste thing.
A completely different approach:
I need to copy & paste text between windows, so I used this to save (copy) the data to local storage. Then, in the other window, I load it out of local storage, using the same key, and I can then 'paste' is as I like.
here's a concise version I use -
function copyToClipboard(data) {
angular.element('<textarea/>')
.css({ 'opacity' : '0', 'position' : 'fixed' })
.text(data)
.appendTo(angular.element($window.document.body))
.select()
.each(function() { document.execCommand('copy') })
.remove();
}
I created a directive for copy to clipboard which is using the document.execCommand() method.
Directive
(function() {
app.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) {
textarea.val(toCopy);
body.append(textarea);
textarea[0].select();
try {
var successful = document.execCommand('copy');
if (!successful) throw successful;
} catch (err) {
console.log("failed to copy", toCopy);
}
textarea.remove();
}
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function (e) {
copy(attrs.copyToClipboard);
});
}
}
})
}).call(this);
Html
<button copy-to-clipboard="Copy Me!!!!" class="button">COPY</button>
BTW, if using Angular to copy to clipboard with a Chrome Packaged App, do the following:
Put a function in your controller like:
$scope.copyUrlToClipboard = function(url) { var copyFrom = document.createElement("textarea"); copyFrom.textContent = url; var body = document.getElementsByTagName('body')[0]; body.appendChild(copyFrom); copyFrom.select(); document.execCommand('copy'); body.removeChild(copyFrom); this.flashMessage('over5'); }
I had the same issue and I used angular-clipboard feature[1] which uses new Selection API and Clipboard API available in the latest browsers.
First we have to install angular-clipboard lib, i'm using bower.
$ bower install angular-clipboard --save
To import the module use following in html.
<script src="../../bower_components/angular-clipboard/angular-clipboard.js"></script>
To set values to element using $scope in controller
$scope.textToCopy = 'Testing clip board';
Load the clipboard module using,
angular.module('testmodule', ['angular-clipboard']);
This works for Chrome 43+, Firefox 41+, Opera 29+ and IE10+.
Its simple & worked fine.
[1] https://www.npmjs.com/package/angular-clipboard
Thanks,