AngularJS $compile and external directive ui-codemirror

257 views Asked by At

I am trying to use the external module, angular-ui-codemirror, to display the $element.html() of an enclosing AngularJS directive in a code-formatted block, using nested directive ui-codemirror.

If you want to know why I need to do this, look here.

I can easily see from examples how to get this going with static text. And I can pass the innerHTML of the enclosing directive alright. It just doesn't compile afterward into a ui-codemirror directive.

I see, here, that it is probably necessary to use the $compile service to do this, but I cannot adapt that example to this situation.

Here is some example AngularJS code:

angular.module('articles', ['ui.codemirror']).directive('jsCode', function($compile) {
  return {
    restrict: 'E',
    link: function($scope, $element) {    
      $scope.codeText = $element.html();
      var template = '<div ' +
          'ui-codemirror="{ ' +
            'lineNumbers: true, ' +
            'theme:\'twilight\', ' +
            'readOnly: \'nocursor\', ' +
            'lineWrapping: true, ' +
            'mode: \'xml\'}" ' +
          'ng-bind="codeText"></div>';
      var linkFn = $compile(template);
      var content = linkFn($scope);
      $element.replaceWith(content)
    }
  };
});

and the html:

<js-code>
&lt;html style=&quot;color: green&quot;&gt;
&lt;!-- this is a comment --&gt;
&lt;head&gt;
&lt;title&gt;HTML Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
I mean&amp;quot;&lt;/em&gt;... but might not match your style.
&lt;/body&gt;
&lt;/html&gt;
</js-code>

I created this Plunker to illustrate my dilemma. The first block is unformatted. The second block (static) is formatted.

1

There are 1 answers

0
Sebri Zouhaier On

replace in jsCode directive

'ng-bind="codeText"></div>';

by

'ng-model="codeText"></div>';

and use

$element.text()  

instead of

$element.html()