GithubHelp home page GithubHelp logo

sachinchoolur / ngclipboard Goto Github PK

View Code? Open in Web Editor NEW
387.0 6.0 93.0 728 KB

An angularjs directive to copy text to clipboard without using flash

Home Page: http://sachinchoolur.github.io/ngclipboard/

License: MIT License

JavaScript 100.00%

ngclipboard's Introduction

license travis bower npm

ngclipboard

An angularjs directive to copy text to clipboard without using flash

Angularjs directive for clipboard.js by @zenorocha

Install

You can get it on npm.

npm install ngclipboard --save

Or bower, too.

bower install ngclipboard --save

If you're not into package management, just download a ZIP file.

Setup

First, include angularjs and clipboard.js into your document.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>

Then Include ngclipboard.js.

<script src="dist/ngclipboard.min.js"></script>

Add ngclipboard dependency to your module

var myApp = angular.module('app', ['ngclipboard']);

Finally, add ngclipboard directive to the wanted html element.

<button class="btn" ngclipboard data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
    Copy to clipboard
</button>

Usage

We're living a declarative renaissance, that's why we decided to take advantage of HTML5 data attributes for better usability.

Copy text from another element

A pretty common use case is to copy content from another element. You can do that by adding a data-clipboard-target attribute in your trigger element.

The value you include on this attribute needs to match another's element selector.

example-2

<!-- Target -->
<input id="foo" value="https://github.com/sachinchoolur/ngclipboard.git">

<!-- Trigger -->
<button class="btn" ngclipboard data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
</button>

Cut text from another element

Additionally, you can define a data-clipboard-action attribute to specify if you want to either copy or cut content.

If you omit this attribute, copy will be used by default.

example-3

<!-- Target -->
<textarea id="bar">Mussum ipsum cacilds...</textarea>

<!-- Trigger -->
<button class="btn" ngclipboard data-clipboard-action="cut" data-clipboard-target="#bar">
    Cut to clipboard
</button>

As you may expect, the cut action only works on <input> or <textarea> elements.

Copy text from attribute

Truth is, you don't even need another element to copy its content from. You can just include a data-clipboard-text attribute in your trigger element.

example-1

<!-- Trigger -->
<button class="btn" ngclipboard data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
    Copy to clipboard
</button>

Events

There are cases where you'd like to show some user feedback or capture what has been selected after a copy/cut operation.

That's why we fire custom events such as success and error for you to listen and implement your custom logic.

ngclipboard provides you two attributes called ngclipboard-success and ngclipboard-error to listen the clipboard events and implement your custom logic.

<button class="btn" ngclipboard ngclipboard-success="onSuccess(e);" ngclipboard-error="onError(e);" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">
    Copy to clipboard
</button>
// You can still access the clipboard.js event
$scope.onSuccess = function(e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);

    e.clearSelection();
};

$scope.onError = function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
}

For a live demonstration, open this site and just your console :)

Browser Support

This library relies on both Selection and execCommand APIs. The first one is supported by all browsers while the second one is supported in the following browsers.

Chrome logo Edge logo Firefox logo Internet Explorer logo Opera logo Safari logo
42+ ✔ 12+ ✔ 41+ ✔ 9+ ✔ 29+ ✔ 10+ ✔

The good news is that clipboard.js gracefully degrades if you need to support older browsers. All you have to do is show a tooltip saying Copied! when success event is called and Press Ctrl+C to copy when error event is called because the text is already selected.

License

MIT License

ngclipboard's People

Contributors

beogip avatar graingert avatar idanen avatar manishsaraan avatar martinratinaud avatar reiz avatar romkor avatar sachinchoolur avatar sivalumotune avatar trentrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ngclipboard's Issues

"Module 'ngclipboard' is not available!"

I included ngclipboard as a dependency for my angular application, but that caused the app to fail after serving the app using grunt serve:dist. This is the error

Error: [$injector:modulerr] Failed to instantiate module ngclipboard due to:

Error: [$injector:nomod] Module 'ngclipboard' is not available!

You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I for sure have the right spelling (as you can see from what the error says I used), and I see the ngclipboard code in the generated vendor file. What could be the issue?

Problem with IE 11

We use ngclipboard and when we click the first time nothing happens. You have to click several times to copy it to the clipboard.

For our tests we use the ones you propose on the page GitHub

Copy from model

hi,
I think it is fairly common for angular devs to manipulate models rather than html string ,can we have feature in which we copy rather a model's value than some html?

e.stopPropagation();

How would I call e.stopPropagation(); on this?

I have the click to copy button hovering over another bottom, and the click event is getting sent down to the bottom button, but I'd like to prevent this.

Dynamically triggering button does not copy to clipboard

Hi ,
I have a service that returns data as html table based on parameters and I want that to be copied to the clipboard. If I have that button click programmatically, the onError method is getting fired but when I manually click the same button, onSuccess method is fired and the content gets copied to the clipboard.

I'm in badly need of the programmatic technique to copy the content to clipboard. Can you please guide?

Thanks,
Hemant.

Clipboard is not a constructor

Selection

Hi,
How could I remove text selection after Copy? In your example it's working good
Thanks in advance

copy to clipboard by checkbox not working

it's not working in google chrome v.53. Here is my example:

        <div ng-app="myApp" ng-controller="myController as c">
            <!-- Target/Trigger -->
            <input id="foo" type="checkbox"
                ngclipboard data-clipboard-target="#foo"
                ngclipboard-success="onSuccess(e);" value="Bike" /> I have a bike <br/>
        </div>
(function () {
  'use strict';

  angular.module('myApp', ['ngclipboard']);
  angular.module('myApp').controller('myController', function($scope){
    $scope.onSuccess = function(e){
      console.info('Action:', e.action);
      console.info('Text:', e.text);
      console.info('Trigger:', e.trigger);

      e.clearSelection();
    };
  });
})();

and issue
Uncaught InvalidStateError: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('checkbox') does not support selection.

minimum Angular version?

I couldn't find it in the docs. Package.json states ng > 1.2, just wanted to confirm. What is the minimum supported Angular version?

Doesn't Play Well With Bower

I'm using bower, and as expected, bower install ngclipboard --save installs ngclipboard, and it's dependency, clipboard. However, when loaded with these tags:

    <script type="text/javascript" src="./bower/angular/angular.js"></script>
    <script type="text/javascript" src="./bower/angular-aria/angular-aria.min.js"></script>
    <!--etc.-->
    <script type="text/javascript" src="./bower/clipboard/dist/clipboard.min.js"></script>
    <script type="text/javascript" src="./bower/ngclipboard/dist/ngclipboard.js"></script>

It produces this in the console:

WARNING: Tried to load angular more than once.
module.js:455 Uncaught Error: Cannot find module 'clipboard'

Referencing this code:

    // Check for CommonJS support
    if (typeof module === 'object' && module.exports) {
      angular = require('angular');
      Clipboard = require('clipboard');    //this line in particular
      module.exports = MODULE_NAME;
    } else {
      angular = window.angular;
      Clipboard = window.Clipboard;
    }

If I install using npm, it all works, even if I keep the bower source tags.

The project has node packages in the same directory, including angular, which explains why the log says WARNING: Tried to load angular more than once. instead of something like module.js:454 Uncaught Error: Cannot find module 'angular'.

Any way to use an angular variable in data-clipboard-text?

Hi, is there any way I can use an angular variable as the data-clipboard-text? I tried just putting the variable name in there with the curly braces around it but it just copies the name. I know I can use a hidden input and ng-value but that doesn't work well on mobile.

ctrl+c not working on Safari

Hi,

Using Safari the library send out the error event correctly, but it doesn't seem to copy the text if i use cmd-C combination. Even the online example doesn't seem to work.
I'm using the "data-clipboard-text" attribute and Safari 9.0.3 for Mac.

Stop propagation is impossible to use in conjunction with this

Because of these lines in good-listener which is what clipboard.js uses for listening to clicks, specifically because it uses event delegation and listens on body, it's consequently impossible to use this directive inside anything that needs to stop propagation because then the click is never triggered on body. For instance, my use case (simplified) is like this:

<div class="container" ng-click="open = !open">
  <div class="row-header">
    <!-- Header content -->
  </div>
  <div class="body-content animate-show" ng-show="open" stop-propagation>
    <span ngclipboard data-clipboard-text="This will never be copied" ngclipboard-success="doSomething()">Copy</span>
  </div>
</div>

Obviously, that's contrived, cause here you could easily move the ng-click further down, but the point it illustrates can't always be worked around. I mean, if any parent, anywhere on the page above ngclipboard calls stopPropagation, the text will never be copied.

There's an issue on clipboard.js related to this here, but I don't see how the proposed solution there could be implemented using this directive.

Tooltip doesn't appear

Hi,

there is a specific configuration to show the tooltip? Because I follow your default configuration and, when I copy, the tooltip "copied!" doesn't appear.

Here's my configuration:

<button class="btn btn-default btn-xs" ngclipboard data-clipboard-text="{{item.url}}">
   <i class="fa fa-clipboard"></i>
</button>

item.url is a string that return from a ng-repeat

Used in a directive - generation at the same milisecond

Hi Sachin,
Thanks for this great work!
I used your script in a directive that is used many times on my page. It appears that my copy buttons had weird behavior when 2 buttons were rendered at the same milisecond.
In order to fix that, I changed:
attr("id","ngclipboard"+Date.now())
to
attr("id","ngclipboard"+Math.round(Math.random() * 1000000))

Hope this helps someone!

ngClipboard: suddenly chrome issues "Illegal constructor" using ngClipboard

Thanks for the directive... 1 question...

I want to copy a URL that is located with in an Angular variable i.e. in html it reads: {{focus.link}}

But Directive doesn't see the value of the variable, and it just copies the string "focus.link"

Any ideas?

bower dependencies OOD

bower-asset/ngclipboard 1.1.1 requires bower-asset/clipboard ~1.5.5 -> no matching package found.

IIFE

the IIFE in the dist is messing with minification,
currently it is
(function() { }());
should be
(function() { })();

Anyone tried running this in Electron?

I'm building a desktop app using Electron, Angular 1.4.9 and electangular.

When I try to use ngclipboard I get the following errors. I'm not sure if it's Electron or electangular causing the issue. I'm able to use other modules such as angularMoment. Any thoughts?

module.js:455 Uncaught Error: Cannot find module 'angular'Module._resolveFilename @ module.js:455Module._resolveFilename @ reset-search-paths.js:35Module._load @ module.js:403Module.require @ module.js:483require @ internal/module.js:20(anonymous function) @ ngclipboard.min.js:4(anonymous function) @ ngclipboard.min.js:4
angular.js:68 Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module myApp.controllers due to:
Error: [$injector:modulerr] Failed to instantiate module ngclipboard due to:
Error: [$injector:nomod] Module 'ngclipboard' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Publish v1.1.3 to npm

Hi Sachin,

Nice work on the module!
Can you please publish v1.1.3 to npm.

Thanks,

Judd

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.