Skip to content

Instantly share code, notes, and snippets.

@simonbernard
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbernard/8964929 to your computer and use it in GitHub Desktop.
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…
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(/&nbsp;/g, "");
ngModel.$setViewValue(html);
});
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment