将CodeMirror应用于ng-model-bound textarea

7 jquery codemirror angularjs angularjs-directive ui-codemirror

我正在编写一个非常基本的游乐场.出于某种原因,我需要将html面板嵌入到AngularJS应用程序中.

这个版本中,我将一个JQuery更改侦听器放到CSS面板中,并将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>
Run Code Online (Sandbox Code Playgroud)

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();
    }
 });
Run Code Online (Sandbox Code Playgroud)

有谁知道如何使CodeMirror在这里工作?

另外,在AngularJS应用程序中使用JQuery事件侦听器真的是个坏主意吗?编写使用AngularJS + CodeMirror的游乐场的最佳结构是什么?

编辑1:我找到了这个线程,然后我做了一个codeMirror指令,它不能正常工作.DevTools显示我的错误TypeError: textarea.getAttribute is not a functionCodeMirror.fromTextArea(...).

Sur*_*h B 2

Here我在 angularjs 中添加了 Demo For Code 镜像。我希望它能帮助你...

这里演示