我正在尝试创建一个执行“语法突出显示”的编辑器,它相当简单:
yellow -> <span style="color:yellow">yellow</span>
我也使用<code contenteditable>
html5 标签来替换<textarea>
,并有颜色输出。
我从 angularjs 文档开始,并创建了以下简单指令。它确实有效,除了它不contenteditable
使用生成的 html 更新区域。如果我使用 aelement.html(htmlTrusted)
而不是ngModel.$setViewValue(htmlTrusted)
,一切正常,除了光标在每次按键时跳到开头。
指示:
app.directive("contenteditable", function($sce) {
return {
restrict: "A", // only activate on element attribute
require: "?ngModel", // get ng-model, if not provided in html, then null
link: function(scope, element, attrs, ngModel) {
if (!ngModel) {return;} // do nothing if no ng-model
element.on('blur keyup change', function() {
console.log('app.directive->contenteditable->link->element.on()');
//runs at each event inside <div contenteditable>
scope.$evalAsync(read);
});
function read() {
console.log('app.directive->contenteditable->link->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 = '';
}
html = html.replace(/</, '<');
html = html.replace(/>/, '>');
html = html.replace(/<span\ style=\"color:\w+\">(.*?)<\/span>/g, "$1");
html = html.replace('yellow', '<span style="color:yellow">yellow</span>');
html = html.replace('green', '<span style="color:green">green</span>');
html = html.replace('purple', '<span style="color:purple">purple</span>');
html = html.replace('blue', '<span style="color:yellow">blue</span>');
console.log('read()-> html:', html);
var htmlTrusted = $sce.trustAsHtml(html);
ngModel.$setViewValue(htmlTrusted);
}
read(); // INITIALIZATION, run read() when initializing
}
};
});
html:
<body ng-app="MyApp">
<code contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>This <span style="color:purple">text is purple.</span> Change me!</code>
<hr>
<pre>{{userContent}}</pre>
</body>
plunkr:演示(输入yellow
,green
或blue
进入更改我输入区域)
我试过了scope.$apply()
,ngModel.$render()
但没有效果。我必须错过一些非常明显的东西......
我已经阅读的链接:
- 别人的 plunker 演示 1
- 别人的 plunker 演示 2
- angularjs 文档的示例
- $sce.trustAsHtml stackoverflow 问题
- setViewValue 堆栈溢出问题
- setViewValue 不更新 stackoverflow 问题
任何帮助深表感谢。请参阅上面的 plunker 演示。