DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • About Using Regexp in Nginx Map
  • Improving ui-select Control
  • 50+ Top Angular Interview Questions and Answers
  • Mule 4: Creating Global Custom Functions in Dataweave 2.0

Trending

  • Continuous Integration vs. Continuous Deployment
  • Using Open Source for Data Integration and Automated Synchronizations
  • Message Construction: Enhancing Enterprise Integration Patterns
  • The Emergence of Cloud-Native Integration Patterns in Modern Enterprises

AngularJS – Copy to Clipboard Directive

A tutorial on how to create a "copy to clipboard" behavior in an AngularJS app.

Gil Fink user avatar by
Gil Fink
·
Nov. 18, 15 · Tutorial
Like (7)
Save
Tweet
Share
22.53K Views

Join the DZone community and get the full member experience.

Join For Free

Yesterday I was requested to create a “copy to clipboard” behavior in an AngularJS application I’m building. The main idea was to mark some content which has a meaning and to enable the user to copy the “meaning” to the clipboard by pressing a button.

Here is the directive I ended up with:

(function () {
    'use strict';
    angular.
        module("demo").
        directive("copyToClipboard", copyClipboardDirective);

    function copyClipboardDirective() {
        var clip;

        function link(scope, element) {
            function clipboardSimulator() {
                var self = this,
                    textarea,
                    container;

                function createTextarea() {
                    if (!self.textarea) {
                        container = document.createElement('div');
                        container.id = 'simulate-clipboard-container';
                        container.setAttribute('style', ['position: fixed;', 'left: 0px;', 'top: 0px;', 'width: 0px;', 'height: 0px;', 'z-index: 100;', 'opacity: 0;', 'display: block;'].join(''));
                        document.body.appendChild(container);

                        textarea = document.createElement('textarea');
                        textarea.setAttribute('style', ['width: 1px;', 'height: 1px;', 'padding: 0px;'].join(''));
                        textarea.id = 'simulate-clipboard';
                        self.textarea = textarea;
                        container.appendChild(textarea);
                    }
                }

                createTextarea();
            }

            clipboardSimulator.prototype.copy = function() {
                this.textarea.innerHTML = '';
                this.textarea.appendChild(document.createTextNode(scope.textToCopy));
                this.textarea.focus();
                this.textarea.select();
                setTimeout(function() {
                    document.execCommand('copy');
                }, 20);
            };

            clip = new clipboardSimulator();

            element[0].addEventListener('click', function() {
                clip.copy();
            });
        }

        return {
            restrict: 'A',
            link: link,
            scope: {
                textToCopy: '='
            }
        };
    }
}());

The main idea is borrowed from a StackOverflow answer – How does Trello access the user’s clipboard?

I use an invisible element container to wrap a textarea which will hold the copied content. The directive model, textToCopy, is used to get the text that I copy, which means that all the directive user needs to do is to hold in that model the text he/she wants to copy. Once the button is clicked, I put the textToCopy data in the textarea, call the textarea select function and use the document.execCommand(‘copy’) call to force the browser to copy the selected content to the clipboard.

Here is how you can use the directive on top of an element:

<button copy-to-clipboard text-to-copy="vm.someText">Copy to Clipboard</button>

someText will be a property of the vm object which will hold the text you want to copy (in my application vm is a controller that is used with the controllerAs property).

I hope that you will find this directive useful.

Directive (programming)

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • About Using Regexp in Nginx Map
  • Improving ui-select Control
  • 50+ Top Angular Interview Questions and Answers
  • Mule 4: Creating Global Custom Functions in Dataweave 2.0

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: