AngularJS对带有contentEditable的普通元素directive一个ng-model

[code lang=”js”]

‘use strict’;
angular
.module(‘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(更新ui)
ngModel.$render = function() {
element.html(ngModel.$viewValue || ”);
};
// Listen for change events to enable binding(添加事件)
element.on(‘blur keyup change’, function() {
scope.$apply(readViewText);
});
// No need to initialize, AngularJS will initialize the text based on ng-model attribute
// Write data to the model
function readViewText() {
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);
}
}
};
});
[/code]
Well-Crafted Apps: How make a two-way binding to your contenteditable DIV or SPAN using AngularJS directives

发表评论

邮箱地址不会被公开。 必填项已用*标注