var MyApp = angular.module('MyApp', []); MyApp.directive('safePaste', [function() { /* * Private Variables */ // Holds special characters to be replaced with safe versions var specialCharacters = ["–", "’"], normalCharacters = ["-", "'"] /* * Private Methods */ // Replaces invalid characters with safe versions function replaceInvalidCharacters (string) { var regEx; // Loop the array of special and normal characters for (var x = 0; x < specialCharacters.length; x++) { // Create a regular expression to do global replace regEx = new RegExp(specialCharacters[x], 'g'); // Do the replace string = string.replace(regEx, normalCharacters[x]); } return string; } // Does the magic function handlePaste (event) { // We got this event.preventDefault(); // Get the plain text var plainText = event.clipboardData.getData('text/plain'); // Clean up the text var cleanText = replaceInvalidCharacters(plainText); // Tell the browser to insert the text document.execCommand('inserttext', false, cleanText); // Backup to the event.preventDefault() return false; } /* * Declaration */ var declaration = {}; declaration.restrict = 'A'; declaration.link = function(scope, element, attr) { // Attach the paste handler element.on('paste', handlePaste); // Register to remove the paste handler scope.$on('$destroy', function() { element.off('paste', handlePaste); }); }; return declaration; } ]);
<div ng-app="MyApp"> <p>Paste some bad content below (from MS Word or something)</p> <div id="test" contenteditable="true" safe-paste></div> </div>