【发布时间】:2016-02-18 16:21:39
【问题描述】:
我正在尝试创建一个执行“语法高亮”的编辑器, 这很简单:
yellow -> <span style="color:yellow">yellow</span>
我也是用<code contenteditable>html5标签代替<textarea>,并有颜色输出。
我从 angularjs 文档开始,并创建了以下简单指令。它确实有效,除了它不使用生成的 html 更新 contenteditable 区域。
如果我使用element.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:demo(输入 yellow、green 或 blue 到更改我的输入区域)
我试过scope.$apply(),ngModel.$render(),但没有效果。我必须错过一些非常明显的东西......
我已经阅读过的链接:
- others' plunker demo 1
- others' plunker demo 2
- angularjs documentation's example
- $sce.trustAsHtml stackoverflow question
- setViewValue stackoverflow question
- setViewValue not updating stackoverflow question
非常感谢任何帮助。请参阅上面的 plunker 演示。
【问题讨论】:
标签: angularjs angularjs-directive contenteditable angularjs-sce