Last active
August 29, 2015 13:56
-
-
Save simonbernard/8964929 to your computer and use it in GitHub Desktop.
I spent some reasonable time finding out, how to properly set-up a contenteditable directive in angularjs. What I wanted was a directive that preserves all new-line characters but I did not want any HTML code in the model. I ended up with below directive which replaces the tags with new-line characters. I used this directive on a contenteditable…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive('contenteditable', function() { | |
return { | |
restrict: 'A', | |
require: '?ngModel', | |
link: function(scope, element, attrs, ngModel) { | |
if(!ngModel) | |
return; | |
// model -> view | |
ngModel.$render = function() { | |
element.html(ngModel.$viewValue); | |
}; | |
// view -> model | |
element.bind('keyup', function() { | |
scope.$apply(function() { | |
var html = element.html(); | |
html = html.replace(/<br>/g, "\n"); | |
html = html.replace(/<p>/g, "\n"); | |
html = html.replace(/<\/p>/g, ""); | |
html = html.replace(/<div>/g, "\n"); | |
html = html.replace(/<\/div>/g, "\n"); | |
html = html.replace(/ /g, ""); | |
ngModel.$setViewValue(html); | |
}); | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment