我刚刚开始了解 Angularjs 并在文档中看到了以下内容,我该如何调整它以使用 ng-bind-html 而不是 ng-model。我假设同时使用 ng-bind-html 和 ng-model 会发生冲突吗?
angular.module('customControl', []).
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);
}
}
};
});
来自 https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
我目前正在使用如下的 ng-bind-html 指令(虽然不是双向绑定(bind),但效果很好):
<div ng-bind-html="person.nameHtml" contenteditable="true"></div>
最佳答案
根据问题的评论,答案是您可以使用 ngModel
指令:
<div ng-bind-html="person.nameHtml"
contenteditable="true"
ng-model="person.nameHtml">
</div>
关于javascript - 如何在 Angular js 中使用 ng-bind-html 实现对 contenteditable 元素的双向绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23445516/