angular其實不再需要input和textarea標簽來做輸入功能,只需要給div加個h5屬性contenteditable="true"即可使用ng-model實現雙向綁定,和高度自適應的功能,
蘋果手機不支持h5屬性 contenteditable="true",需要在這個div中添加樣式-webkit-user-select:text
這里的ng-model只能綁定對象中的某一個元素,如ng-model=“content.item”
div{
-webkit-user-select:text;
}
/*為空時顯示 element attribute content*/
div
:empty:before{
content: attr(placeholder); /* element attribute*/
color:#red; /*content: 'this is content';*/
}
/*焦點時內容為空*/
div
:focus:before{
content:none;
}
html代碼
<div contenteditable="true" class="texttitle zkht-create-answer" ng-model="content.item"></div>
directive.js
app.directive('contenteditable', function() {
return {
restrict: 'A', // 只用於屬性
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) {
return;
}
// 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(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);
}
}
};
