Tips for transforming a JavaScript function into an AngularJS directive

A handy JavaScript function that allows you to copy text from an input field to your clipboard when you click a button. Here's how it works:

<script type="text/javascript">
    (function () {
        'use strict';
        // Listen for click events
        document.body.addEventListener('click', copy, true);
        // Event handler
        function copy(e) {
            // Find target element
            var
              t = e.target,
              c = t.dataset.copytarget,
              inp = (c ? document.querySelector(c) : null);
            // Check if element is selectable
            if (inp && inp.select) {
                // Select text
                inp.select();
                try {
                    // Copy text
                    document.execCommand('copy');
                    inp.blur();
                }
                catch (err) {
                    alert('please press Ctrl/Cmd+C to copy');
                }
            }
        }
    })();
</script>

Usage example:

<button id="CopyTextBtn" autofocus
        type="submit"
        class="uui-button lime-green"
        data-copytarget="#ClientsURL"
        ng-click="closeThisDialog('Cancel')">
    Copy
</button>

I attempted to implement this functionality using a directive in my app:

appModule.directive('data-copytarget', function () {
    return {
        scope: {},
        link: function (scope, element)
        {
            // Listen for click events
            document.body.addEventListener('click', copy, true);
            // Event handler
            function copy(e) {
                // Find target element
                var
                  t = e.target,
                  c = t.dataset.copytarget,
                  inp = (c ? document.querySelector(c) : null);
                // Check if element is selectable
                if (inp && inp.select) {
                    // Select text
                    inp.select();
                    try {
                        // Copy text
                        document.execCommand('copy');
                        inp.blur();
                    }
                    catch (err) {
                        alert('please press Ctrl/Cmd+C to copy');
                    }
                }
            }
        }
    };
});

Unfortunately, I encountered issues with this implementation and it did not work as expected.

Answer №1

When working with the link function in a directive, you have access to scope, element, and attrs as arguments. One way to handle click events is by using

elem.bind('click', function() { })
, or you can also utilize
angular.element(document).find('body');
to bind the click event to it.

appModule.directive('data-copytarget', function () {
    return {
        scope: {},
        link: function (scope, elem)
        {
            // handling click events
            elem.bind('click', function() {
                // finding the target element
                var
                  t = e.target,
                  c = t.dataset.copytarget,
                  inp = (c ? document.querySelector(c) : null);
                // checking if element is selectable
                if (inp && inp.select) {
                    // selecting text
                    inp.select();
                    try {
                        // copying text
                        document.execCommand('copy');
                        inp.blur();
                    }
                    catch (err) {
                        alert('please press Ctrl/Cmd+C to copy');
                    }
                }                
        }
    };
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to save multiple identification numbers in localStorage with JavaScript

I am looking to implement a favorites feature on my website using HTML, CSS, JavaScript, and JSON. The JSON file is loaded through AJAX and users can search for devices to add to their favorites using sessionStorage and localStorage. However, I'm faci ...

Images in a horizontal dropdown selection menu

Currently, I have a traditional select dropdown that is data-bound with Angular. <select class="form-control" ng-model="category"> <option value="work">Work</option> <option value="home">Home</option> <option valu ...

Unable to utilize JavaScript from the imported AJAX page XMLHttpRequest

I have implemented a bit of AJAX functionality using XMLhttpRequest, where it replaces a div and functions as expected. However, I am facing difficulty in getting the JavaScript code in the included AJAX page to execute. Is there a way to run JavaScript f ...

Ionic allows the screen to automatically move up when the keypad is activated

I am in the process of building a mobile app using Ionic version 1. I would like for the screen to automatically scroll up whenever an input field (such as text, tel, email, number, etc.) is selected. Does anyone have suggestions on how to achieve this? ...

The pairing of RequireJS and Toaster

I am facing an issue with integrating Toaster into my demoApp that utilizes RequireJS. Below is the code snippet: (function () { require.config({ paths: { 'angular': 'bower_components/angular/angular', ...

What is the best way to apply three unique classes to multiple div elements using jQuery?

Utilizing jQuery to assign three different classes to my div elements with the same name. Here is the HTML: <div class="main-class"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div& ...

Establish a trigger in mongoDB that monitors changes in document values and triggers an email notification

Hello there! As a newcomer to MongoDB and the world of web development, I have a question that I hope you can help me with. I am looking to send out emails based on the time difference between the current time and the event time stored in the event model a ...

Using the information selected from the dropdown menu, the table was refined through an AJAX request

Having a small issue with ajax when working on my project. I have two actions in the view: <body> @Html.Action("SetSearchFilter") @Html.Action("FillTable") </body> The first action is a DropDownList: @Html.LabelFor(m => m.Manager, ...

Revise directive following the dynamic addition of elements

My Objective: I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time. The Challenge: Upon dynamically adding custom elements to the view, they appear as raw HTML without the directi ...

ng-switch is failing to function in specific instances

I'm currently constructing a login module using AngularJS. Below is the code snippet: For the main page HTML: <div id='main' ng-controller='LoginController'> <div class='yomate-header'> <div c ...

Developing a single page application with AngularJS and ExpressJS that involves dynamically injecting templates

I'm currently developing an application using angularJS and nodejs/expressjs. Upon accessing the application's URL, I need to verify if the user is already logged in. If they are, I want to display the homepage of the application. Otherwise, I n ...

Testing a service with $resource using unit tests

Struggling to write a unit test for an existing service and puzzled by the unexpected data appearing in the results, leading to test failures. Let's take a look at the key components: Service Method: function createAddressType(newAddressType) { var ...

New and personalized bindings in knockout.js for dynamically updating a dropdown menu based on the selection in another dropdown menu

I have been using knockout for a few months now and have been getting along just fine. However, I recently encountered an issue where I cannot update the options within a SELECT tag because the ajax methods that retrieve data from the server are inside a ...

Using InputAdornment with MUI AutoComplete causes the options list to disappear

I created a custom AutoComplete component with the following structure: https://i.sstatic.net/xcv9y.png <Autocomplete freeSolo size="small" id="filter-locks-autocomplete" options={json_list ? json_list : []} groupBy={(optio ...

Exploring the functionality of Array.prototype.includes() in Angular 7 with PhantomJS testing

While testing components in my Angular application, I noticed that unit tests utilizing Array.prototype.includes() are successful in Chrome but fail when executed with PhantomJS. I found some suggestions in the responses to this question related to a simi ...

The video continues to play despite me opening the modal

I am facing an issue with a video tag where the video keeps playing in the background even when my modal is open. I want the video to stop playing once the modal is opened. Here is the code snippet: const videoRef = useRef(null); function pauseVideo() ...

Create an AngularJS factory that can be used multiple times

Once I realized that $resource wasn't quite what I was looking for, I set out to create my own factory to manipulate my data. Now, as I work on the initial draft of this factory, I'm contemplating the best approach to reuse this code for differen ...

What is the method to obtain the selector string for an HTML node element?

Essentially, my goal is to extract the selector string from an HTML element. Specifically, I want to start with the HTML element and retrieve its selector string (for example: button#myButton) function onclicked(e){ console.log(e.target); // This returns ...

Basic AngularJS application for showcasing the present date

I enrolled in a online course through edX focused on AngularJS. Unfortunately, I've hit a roadblock with one of the labs. The platform doesn't provide solutions and the support forum isn't very helpful, so I'm turning to this community ...

Performing a cross-domain JSON Get request with JQuery

Struggling with a simple JSON get request to an API on a domain that I don't have control over. Here's the code I'm using: $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://pu ...