Created
September 17, 2016 14:25
-
-
Save jerrybendy/69823e66f471912ffa2a0464887bb9f8 to your computer and use it in GitHub Desktop.
Angular 1.x 为元素添加 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
/** | |
* 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