Angular [ngPaste] triggers when content is pasted

Is there a way to trigger a function on the "Paste" event in an input field using Angular 1.1.5? I am aware of the ng-change directive, but it fires every time the input changes. I only need it to trigger once after the initial paste.

For instance, I have a URL input field and I want to perform a specific action after the user pastes a URL into it. The user should also be able to manually enter the URL and trigger the function by pressing Enter.

--

Update: Starting from Angular 1.2.0, there is a native ngPaste directive available.

Answer №1

Starting from Angular version 1.2.0, a new directive called ngPaste was introduced for handling paste events. You can implement it in the following manner:

<input type='text' ng-paste='handlePaste($event)'>

If you want to pass the pasted value directly, you can do so using the code below:

<input type='text' ng-paste='handlePaste($event.clipboardData.getData('text/plain'))'>

Answer №2

When writing a function, remember to include the originalEvent

 <textarea onpaste="handlePaste(event)"></textarea>

The function should look like this:

function handlePaste(e) {
    console.log(e.originalTarget.clipboardData.getData('text'));
}

Answer №3

Here is a solution I came up with to address browsers that do not support clipboard API. This method should be compatible with any browser that angular framework supports.

Here is the HTML code:

<input type="text" ng-paste="copyPasted($event)">

And here is the JavaScript code:

$scope.copyPasted = function ($event){
    if(typeof $event.originalEvent.clipboardData !== "undefined"){
        $scope.handlePastedData($event.originalEvent.clipboardData.getData('text/plain'));
    } else { // To accommodate browsers without clipboard API (such as IE and older browsers)
        $timeout(function(){
            $scope.handlePastedData(angular.element($event.currentTarget).val());
        });
    }
};

Answer №4

I have successfully incorporated a solution to sanitize copied text using a custom filter that takes into account the current input selection, including support for IE11.

JS:

vm.pasteInput = pasteInput;

function pasteInput(ev){
  var pastedData ='';
  var domElement = ev.currentTarget;

  if(typeof ev.originalEvent.clipboardData !== "undefined"){
    pastedData = ev.originalEvent.clipboardData.getData('text/plain');
  } else if(window.clipboardData){
    pastedData = window.clipboardData.getData('Text');
    ev.returnValue = false;
  }

  pastedData = $filter('inputtext')(pastedData);

  // insert at correct position within selection
  if (document.selection) { // IE11
    domElement.focus();
    var sel = document.selection.createRange();
    sel.text = pastedData;
    domElement.focus();
  } else if (domElement.selectionStart || domElement.selectionStart === 0){
    var startPos = domElement.selectionStart;
    var endPos = domElement.selectionEnd;
    domElement.value = domElement.value.substring(0, startPos) + pastedData + domElement.value.substring(endPos, domElement.value.length);
    domElement.focus();
    domElement.selectionStart = startPos + pastedData.length;
    domElement.selectionEnd = startPos + pastedData.length;
  } else {
    domElement.value += pastedData;
    domElement.focus();
  }

  ev.stopPropagation();
  ev.preventDefault();

  // update model
  vm.input.value = domElement.value;

}

HTML:

<input type="text" ng-model="vm.input.value" ng-paste="vm.pasteInput($event)" />

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

Using jQuery to track the status of checkboxes

Changing the checkbox status using the code: $(this).attr("checked", 'checked'); However, when trying to check the checkbox status afterwards, I received the following results: $(this).attr('checked'): "checked" $(this).is(':chec ...

Execute a separate function when clicking on certain buttons without interfering with the buttons' original onclick function (which has already been assigned) - JavaScript

While I am still relatively new to JavaScript and learning, I have developed a webpage with multiple buttons that trigger different functions on click events. However, I would like to additionally call another function when any of these buttons are clicked ...

I can't figure out why the callback function for my $.get() request is not being triggered when I send data to the Express

Could anyone help me understand why my callback function is not being called properly? $.get("http://localhost:8080/", msg, function(data) { alert("Data" + data); }); It seems like the server receives the reque ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

I am looking to include an icon in an angular tab to facilitate its closure using ui-bootstrap

I am working on a set of tabs that include a plus Bootstrap icon to dynamically add a tab. var app = angular.module('plunker', ['ui.bootstrap']); app.controller("TabsParentController", function ($scope) { var setAllInactive ...

What is causing the click event handler to only function on the initial page?

Within my code for the "fnInitComplete" : function(oSettings, json), I am utilizing a selector like $('[id^=f_]').each(function (). The data for Datatables is retrieved server-side and "bProcessing":true I am aware that my selectors are only ef ...

Arranging CouchDB/Couchbase view based on the quantity of keys

Looking to create a view that displays the top 10 tags used in my system. While it's simple to get the count using _count in the reduce function, the list is not sorted by the numbers. Is there a way to accomplish this? function(doc, meta) { if(doc ...

retrieving the selected date from the calendar widget

I'm utilizing jQuery's datepicker to collect date inputs from users. The form is structured as below: <form id="myform" action="/graphs/get_builds" method="post"> Start: <input type="text" id="start" /> End: <input type="t ...

Pagination of AJAX result on the client side using jQuery

My issue revolves around pagination in AJAX. I want to avoid overwhelming my search result page with a long list of returned HTML, so I need to split it into smaller sections. The Ajax code I am currently using is: $.ajax({ url: "getflightlist.php?pa ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...

The context menu event fails to activate on browsers running iOS 13.1 and higher when attempting to select text

After updating the iOS version to 13.1, we encountered an issue where the long-press context menu event is not triggering in the browser. Instead, the default browser context menu is being displayed. Our goal is to hide these context menus. !DOCTYPE htm ...

Is it possible to retrieve the ng-model name from an element?

Is there a way to determine the ng-model of the active element? Suppose I have document.activeElement, how can I identify its corresponding ng-model? <input ng-model="myModel"> For example, if the above input field is active, how can I determine th ...

Angular's inline style manipulation fails to function in IE browser

I am facing an issue with setting the position of a div based on the return value of a function in an angular controller Although it works fine in FireFox and Chrome, Internet Explorer is interpreting {{position($index)}}% as a literal string value, resul ...

Tips for adding content to a textarea with JavaScript without disrupting the editing history

I have a specific requirement where I want the user to be able to highlight text in a textarea, then press ctrl + b to automatically surround that selected text with stars. Here is what I envision happening: 1) The initial content of the textarea is: "he ...

Ag-Grid's external filtering feature does not update when there are changes in the state

I've been having trouble getting Ag-Grid's external filtering to respond to changes in state. Despite updating isExternalFiltered, the value of this variable in the doesExternalFilterPass callback remains unchanged. I attempted supplying a key to ...

Unexpected changes are observed in the size of DIV elements when adjusting the SVG viewBox

My aim is to make the <svg> element have the same dimensions for the viewBox as the <div> it is inside. This means that the viewBox values need to match the dimensions of the containing <div>. Here is an example: <div style="width ...

`I am unable to locate the JSON file within Angular 2`

I am experiencing issues loading a .json file from a service file in my Angular2 project. I have set up my Angular2 app using angular-cli and the file structure looks like this: src > app > menu-item > menu-item.service.ts menu-list.json Bel ...

Is the integer node reaching its limit?

Could someone guide me through this? $node -v v0.10.10 $ node > (10000000)>>1 5000000 > (100000000)>>1 50000000 > (1000000000)>>1 500000000 > (10000000000)>>1 705032704 Is it expected that 2^53 is the maximum integer ...

Omit specific TagNames from the selection

How can I exclude <BR> elements when using the statement below? var children = document.getElementById('id').getElementsByTagName('*'); Is there a special syntax for getElementsByTagName that allows me to achieve this, or is the ...