Question: Apply CodeMirror to a ng-model-bound textarea


Apply CodeMirror to a ng-model-bound textarea

Answers 1
Added at 2016-12-27 13:12

I am coding a very very basic playground. For some reason, I need to embed the html panel inside an AngularJS app.

In this version, I put a JQuery change listener to the CSS panel, and applied CodeMirror to the textarea. And it worked.

I felt uncomfortable about having a JQuery event listener inside an AngularJS app, so I decided to bind the CSS panel to the AngularJS app, and made this version. But now, the problem is the CodeMirror code (that I comment below) does not work anymore:


  <div ng-app="myApp" ng-controller="myCtrl">
    <textarea rows=10 cols=40 ng-model="area1">html body area</textarea>
    <textarea id="css" rows=10 cols=40 ng-model="css"></textarea>
  <section id="output">


var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
    $scope.area1 = "<body>default</body>";  
    $scope.$watch('area1', function (json) {
    }, 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);
    }, 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;;

Does anyone know how to make CodeMirror work here?

Additionally, is it really a bad idea to use JQuery event listeners inside an AngularJS app? What's the best structure to code this playground that uses AngularJS + CodeMirror?

Edit 1: I found this thread, then I made a codeMirror directive, it does not work well. DevTools shows me an error TypeError: textarea.getAttribute is not a function at CodeMirror.fromTextArea(...).

Answers to

Apply CodeMirror to a ng-model-bound textarea

nr: #1 dodano: 2016-12-29 14:12

Here I added Demo For Code mirror in angularjs. I hope it will help you...

Here Demo

Source Show
◀ Wstecz