forked from omichelsen/angular-clipboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-clipboard.js
84 lines (76 loc) · 2.81 KB
/
angular-clipboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
(function (root, factory) {
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define(['angular'], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('angular'));
} else {
root.angularClipboard = factory(root.angular);
}
}(this, function (angular) {
return angular.module('angular-clipboard', [])
.factory('clipboard', ['$document', function ($document) {
function createNode(text, context) {
var node = $document[0].createElement('textarea');
node.style.position = 'absolute';
node.textContent = text;
node.style.left = '-10000px';
if (context instanceof HTMLElement) {
node.style.top = context.getBoundingClientRect().top + 'px';
}
return node;
}
function copyNode(node) {
try {
// Set inline style to override css styles
$document[0].body.style.webkitUserSelect = 'initial';
var selection = $document[0].getSelection();
selection.removeAllRanges();
node.select();
if(!$document[0].execCommand('copy')) {
throw('failure copy');
}
selection.removeAllRanges();
} finally {
// Reset inline style
$document[0].body.style.webkitUserSelect = '';
}
}
function copyText(text, context) {
var node = createNode(text, context);
$document[0].body.appendChild(node);
copyNode(node);
$document[0].body.removeChild(node);
}
return {
copyText: copyText,
supported: 'queryCommandSupported' in document && document.queryCommandSupported('copy')
};
}])
.directive('clipboard', ['clipboard', function (clipboard) {
return {
restrict: 'A',
scope: {
onCopied: '&',
onError: '&',
text: '=',
supported: '=?'
},
link: function (scope, element) {
scope.supported = clipboard.supported;
element.on('click', function (event) {
try {
clipboard.copyText(scope.text, element[0]);
if (angular.isFunction(scope.onCopied)) {
scope.$evalAsync(scope.onCopied());
}
} catch (err) {
if (angular.isFunction(scope.onError)) {
scope.$evalAsync(scope.onError({err: err}));
}
}
});
}
};
}]);
}));