1

I have an angularjs directive which listens to on paste event of my textarea:

element.on('paste', function (event) {
});

How do i get the pasted text? I tried:

event.clipboardData.getData('text/plain')

... and:

event.originalEvent.clipboardData 

... but both didn't work. Any suggestions would be helpful.

Maciej Jureczko
  • 1,560
  • 6
  • 19
  • 23
AnoojNair
  • 491
  • 3
  • 11
  • 18

1 Answers1

6

It's really simple actually. You can just get the text with element.val() but you need to put it into setTimeout.

I did an example for you.

Working JSFiddle: http://jsfiddle.net/vxcjw45d/

HTML:

<body ng-app="myApp">
    <div ng-controller="myController">
        <textarea paste-example></textarea>
        <div>{{ pastedText }}</div>
    </div>
</body>

Javascript:

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

myApp.controller('myController', function($scope) {
    $scope.pastedText = '';
});

myApp.directive('pasteExample', function(){
    var linkFn = function(scope, element, attrs) {

        element.on('paste', function() {

            setTimeout(function() {
                console.log(element.val());
                scope.pastedText = element.val();
                scope.$apply();
            }, 5);

        });
    };

    return {
        restrict: 'A',
        link: linkFn
    };
});
Hristo Enev
  • 2,421
  • 18
  • 29