0

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
  • Do you need/want to bind the html using the codeText variable? In other words, will the content of that variable change outside of the element? If not you can just use $element.html() when you build the template string - but I think that something within the codemirror lib relies on the element being already in the dom so it doesn't work totally right, even after you click inside of it. See this plnkr.co/edit/2d3Y8Ic9XFbsloBgT7wv?p=preview Commented Jan 27, 2016 at 17:39

1 Answer 1

0

replace in jsCode directive

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

by

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

and use

$element.text()  

instead of

$element.html()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.