Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AngularJS 如何实现复制到剪切板的功能? #29

Open
HappyZiJunLuo opened this issue Aug 15, 2016 · 0 comments
Open

AngularJS 如何实现复制到剪切板的功能? #29

HappyZiJunLuo opened this issue Aug 15, 2016 · 0 comments

Comments

@HappyZiJunLuo
Copy link

HappyZiJunLuo commented Aug 15, 2016

AngularJS如何实现复制到剪切板的功能?

实践方案

上网查资料时发现有很多实现这个功能的例子,我尝试了其中最简单的一种方法,就是利用原生JS
中的document.execCommand('copy')方法实现: 详见参考链接

js部分

toClipboard(content) {
    const copyElement = angular.element(`<span id="ngClipboardCopyId">${content}</span>`);
    const body = injector.get('$document').find('body').eq(0);

    body.append(injector.get('$compile')(copyElement)(injector.get('$rootScope')));
    const ngClipboardElement = angular.element(document.getElementById('ngClipboardCopyId'));
    const range = document.createRange();

    range.selectNode(ngClipboardElement[0]);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    copyElement.remove();
}

html部分

<input type="text" class="code-input" ng-model="vm.arrangeCode">
<button class="btn-function-normal" ng-click="vm.toClipboard(vm.arrangeCode)">复制</button>

用这种方法虽然实现了功能,但有太多的DOM操作,因此不是很理想的方案

其他方案:

  1. 参考ng-clip源码,其中部分代码看不懂,求大神指点 参考链接
  2. 安装依赖库angular-clipboard 参考链接
@HappyZiJunLuo HappyZiJunLuo changed the title AngularJS 实现复制到剪切板的功能 AngularJS 如何实现复制到剪切板的功能 Aug 16, 2016
@HappyZiJunLuo HappyZiJunLuo changed the title AngularJS 如何实现复制到剪切板的功能 AngularJS 如何实现复制到剪切板的功能? Aug 16, 2016
@hjzheng hjzheng added the 问题 label Aug 18, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants