Last active
July 13, 2018 13:22
-
-
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
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
/** | |
* 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(); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not working for me in firefox