Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
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 – JoseM Jan 27 '16 at 17:39

replace in jsCode directive

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

by

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

and use

$element.text()  

instead of

$element.html()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.