Transfer the value of a variable to Ctrl+C

Asked

Viewed 1,180 times

2

Does anyone know if there is a way to transfer the value of a variable to Ctrl+C?

I am working with Angularjs and inside Scope I have a variable that I would like to move to the Clipboard, but I can’t find anything that helps me.

Follows the code:

JS:

(function(){
  'use script';

  angular
    .module('myApp')
    .controller('meuCtrl', meuCtrl);

  meuCtrl.$inject = ['$scope'];

  function meuCtrl($scope){
    $scope.grupos = [
      {
        "numero": 1,
        "nome": "Grupo 1",
        "link": "https://www.google.com/maps",
        "visitado": true,
        "data": "15/09/2017"
      },
      {
        "numero": 2,
        "nome": "Grupo 2",
        "link": "https://mail.google.com/mail/u/0/#inbox",
        "visitado": true,
        "data": "15/09/2017"
      }
    ]
    $scope.copiar = function(teste) {
      // aqui deve ser feita a atribuição
      // clipboard = teste;
    }
  }
})();

Html:

<section ng-controller="meuCtrl">
  <div ng-repeat="grupo in grupos">
    <div ng-click="copiar(grupo.nome)">
      <span>{{grupo.numero}}</span>
    </div>
     <div class="w3-container w3-button">
      <a target="_blank" href="{{grupo.link}}"> <span>{{grupo.nome}}</span> </a>
    </div>
  </div>
</section>

3 answers

3


I found in this reply How do I copy to the Clipboard in Javascript? a script that should work

PS: I know you’re using angular, but nothing prevents you from using normal JS n is even?

See if it helps you.

/*
 * Copia o texto passado por paramêtro para o clipboard.
 * @param {type} text
 * @returns {undefined|Boolean}
 */
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

The use in your Angular should probably look like this:

$scope.copiar = function(teste) {
    copyToClipboard(teste);
}
  • When copying things from other developers cite sources https://stackoverflow.com/a/33928558/1518921, it’s not cool for you to take something done by another and not mention who had the work and still shared for free.

  • 1

    Hello William, really.. I had copied this answer for my use for some time. However I didn’t save the answer to make the link now. I’m sorry I forgot to make the quote at this time.

  • I edited your answer, removing redundancies and adding the use of the script within the scope Angular, so help the author of the question ... if you disagree with something just do the rollback in the edition. See more.

0

Some time ago I needed and used that code. Below, the code and example of use:

(function (angular) {
    'use strict';

    /// Diretiva para simular o Copy to Clipboard
    /// Será copiado o texto passado na diretiva
    /// Uso: <button stk-click-copy="TEXTO A SER COPIADO" type="button"></button>
    angular.module('stkClickCopy', []);
    angular.module('stkClickCopy').service('stkCopy', StkCopy);
    angular.module('stkClickCopy').directive('stkClickCopy', StkClickCopy);

    StkCopy.$inject = ['$window'];
    StkClickCopy.$inject = ['stkCopy'];

    function StkCopy($window) {
        var body = angular.element($window.document.body);
        var textarea = angular.element('<textarea/>');
        textarea.css({
            position: 'fixed',
            opacity: '0'
        });

        return function (toCopy) {
            textarea.val(toCopy);
            body.append(textarea);
            textarea[0].select();

            try {
                var successful = document.execCommand('copy');
                if (!successful) throw successful;
            } catch (err) {
                window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
            }

            textarea.remove();
        }
    }

    function StkClickCopy(stkCopy) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind('click', function (e) {
                    stkCopy(attrs.stkClickCopy);
                });
            }
        }
    }
})(angular);

Save this code to a file js and import it into your project

<script src="stkClickCopy.js"></script>

Add the component to your project:

angular.module('myApp', ['stkClickCopy']);

And use in your view:

<button stk-click-copy="{{ minhaVariavel }}" type="button"></button>

-1

Assign the function directly to Scope. It worked exactly as I needed it, thank you very much.

$scope.copiar = function(text) {
      if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

      } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
          return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
          console.warn("Copy to clipboard failed.", ex);
          return false;
        } finally {
          document.body.removeChild(textarea);
        }
      }
    }

  • 1

    I’m glad you liked the answers! But the best way to thank those who helped you is to mark "accept" the best answer and vote for all who helped you. This way you make sure that whoever wrote the answer gets something in return, as well as making the site cleaner and more useful for everyone. Adding a new answer like this (which is not an answer to the question and should be removed) makes the site more confusing and can get in the way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.