Skip to content

Instantly share code, notes, and snippets.

@jerrybendy
Created September 17, 2016 14:25
Show Gist options
  • Save jerrybendy/69823e66f471912ffa2a0464887bb9f8 to your computer and use it in GitHub Desktop.
Save jerrybendy/69823e66f471912ffa2a0464887bb9f8 to your computer and use it in GitHub Desktop.
Angular 1.x 为元素添加 contenteditable 支持
/**
* contenteditable 支持, 代码来自 http://stackoverflow.com/questions/23047093/contenteditable-in-angular-js
* 对于添加了 contenteditable 属性的元素, 可以直接用 `ng-model` 双向绑定
*/
app.directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment