Skip to content

Instantly share code, notes, and snippets.

@bettysteger
Last active July 13, 2018 13:22
Show Gist options
  • Save bettysteger/696fd2fa529f4951e569 to your computer and use it in GitHub Desktop.
Save bettysteger/696fd2fa529f4951e569 to your computer and use it in GitHub Desktop.
Angular directive to accomplish two-way data binding for contenteditable elements with ng-model
/**
* Two-way data binding for contenteditable elements with ng-model.
* @example
* <p contenteditable="true" ng-model="text"></p>
*/
app.directive('contenteditable', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ctrl) {
// Do nothing if this is not bound to a model
if (!ctrl) { return; }
// Checks for updates (input or pressing ENTER)
// view -> model
element.bind('input enterKey', function() {
var rerender = false;
var html = element.html();
if (attrs.noLineBreaks) {
html = html.replace(/<div>/g, '').replace(/<br>/g, '').replace(/<\/div>/g, '');
rerender = true;
}
scope.$apply(function() {
ctrl.$setViewValue(html);
if(rerender) {
ctrl.$render();
}
});
});
element.keyup(function(e){
if(e.keyCode === 13){
element.trigger('enterKey');
}
});
// model -> view
ctrl.$render = function() {
element.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$render();
}
};
});
@vishnucr
Copy link

not working for me in firefox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment