我正在编写一个非常非常基本的游乐场。出于某种原因,我需要将 html 面板嵌入到 AngularJS 应用程序中。
在这个版本中,我在 CSS 面板上放置了一个 JQuery 更改侦听器,并将 CodeMirror 应用于 textarea。它奏效了。
我对在 AngularJS 应用程序中使用 JQuery 事件监听器感到不舒服,所以我决定将 CSS 面板绑定到 AngularJS 应用程序,并制作了这个版本。但是现在,问题是 CodeMirror 代码(我在下面评论)不再起作用:
HTML:
<body>
<div ng-app="myApp" ng-controller="myCtrl">
HTML:<br>
<textarea rows=10 cols=40 ng-model="area1">html body area</textarea>
<br>CSS:<br>
<textarea id="css" rows=10 cols=40 ng-model="css"></textarea>
</div>
Output:
<section id="output">
<iframe></iframe>
</section>
</body>
JavaScript:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.area1 = "<body>default</body>";
$scope.$watch('area1', function (json) {
render();
}, true);
$scope.css="body {color: red}";
$scope.$watch('css', function (json) {
// CodeMirror does not work anymore
// var cm_opt = { mode: 'css', gutter: true, lineNumbers: false };
// var css_box = document.getElementById("css");
// var css_editor = CodeMirror.fromTextArea(css_box, cm_opt);
render();
}, true);
function render () {
var source = "<html><head><style>" + $scope.css + "</style></head>" +
$scope.area1 +"</html>";
var iframe = document.querySelector('#output iframe'),
iframe_doc = iframe.contentDocument;
iframe_doc.open();
iframe_doc.write(source);
iframe_doc.close();
}
});
有谁知道如何让 CodeMirror 在这里工作?
此外,在 AngularJS 应用程序中使用 JQuery 事件侦听器真的是个坏主意吗?使用 AngularJS + CodeMirror 编写这个游乐场的最佳结构是什么?
编辑 1:我找到了这个线程,然后我做了一个codeMirror 指令,它不能正常工作。DevToolsTypeError: textarea.getAttribute is not a function
在CodeMirror.fromTextArea(...)
.