ng-paste and onpaste, how to preserve/get existing text while pasting new text

447 Views Asked by At

I'm using ng-paste and onpaste like this,

<input type="text" class="form-control" ng-trim="false" ng-model="x.value" select-on-click ng-paste="paste($event, x)" onpaste="return false;" id="input{{$index}}" 

The input has text some<CURSOR>data (where the <CURSOR> represents the position of the cursor)

When I press Cmd + V the paste event is called,

$scope.paste = function(event, data) {
      console.log('paste event', event);
}

It works, but I can only get the pasted text, what I want is some<PASTED DATA>data, any ideas?

P.S I had to use onpaste="return false;", otherwise the text become <PASTED DATA><PASTED DATA>

1

There are 1 best solutions below

0
Roland On

You could use input element's selectionStart/selectionEnd properties to do the trick.

   function onPaste(event) {
            var input = event.target;
            var start = input.selectionStart;
            var end = input.selectionEnd;
            var originString = input.value;
            var myContent = "<PASTED DATA>";
            input.value = originString.substring(0, start) + myContent + originString.substring(end, originString.length);
            event.preventDefault();
            var currentPosition = (originString.substring(0, start) + myContent ).length;
            setTimeout(function () {
                input.focus();
                input.setSelectionRange(currentPosition, currentPosition);
            }, 0);
        }