jquery - 将 CodeMirror 应用于 ng-model-bound 文本区域

标签 jquery angularjs angularjs-directive codemirror ui-codemirror

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

this version ,我将 JQuery 更改监听器放置到 CSS 面板,并将 CodeMirror 应用于文本区域。结果成功了。

我对 AngularJS 应用程序内有 JQuery 事件监听器感到不舒服,所以我决定将 CSS 面板绑定(bind)到 AngularJS 应用程序,并制作 this version 。但现在,问题是 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 编写这个 Playground 的最佳结构是什么?

编辑1:我发现this thread ,然后我做了一个codeMirror directive , 它不好用。 DevTools 在 CodeMirror.fromTextArea(...) 处向我显示错误 TypeError: textarea.getAttribute is not a function

最佳答案

这里我在angularjs中添加了Demo For Code镜像。希望对您有所帮助...

Here Demo

关于jquery - 将 CodeMirror 应用于 ng-model-bound 文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41345286/

相关文章:

angularjs - 保存后项目消失

AngularJS $watch 在第一次更新后数组失败

javascript - XML解析选项-php或jquery

javascript - 使用 JavaScript 将对象转换为数组

javascript - Jasmine - 模拟 spy On.and.callFake http成功错误

javascript - AngularJS 上的函数启动次数过多

javascript - ngRepeat 中简单指令和相同指令之间的空间不同

c# - 如何从字符串中获取html元素?

javascript - 如何在位置 0 限制零

javascript - Json 字符串化然后从 URL 解析