1

I'm trying to get syntax highlighting for all code elements inside a dynamically added html which will be added to the current page with ng-bind-html.

<div ng-repeat="activity in activities">
    <h3>{{activity.title}}</h3>
    <div ng-bind-html="activity.text">
    </div>
</div>

The activity.text variable contains something like this:

<p>This is a paragraph with some code following.</p>
<pre><code class="lang-python">
s = "Python syntax highlighting"
print s
</code></pre>
<p>some other HTML elements </p>

This works so far but without syntax highlighting. So I've added highlightjs and angular-highlightjs. I've changed <div ng-bind-html="activity.text"> to <div hljs ng-bind-html="activity.text"> The problem now is that combining the ng-bind-html and the hljs directives is not working as expected. It does not add syntax highlighting to the code tag (pre code) but to the whole html content.

Is there a better way to get syntax highlighting for dynamically added content?

3
  • Possible duplicate of Dynamic Syntax Highlighting with AngularJS and Highlight.js Commented Jan 6, 2016 at 16:33
  • Oh thank you for finding this. I'll try this asap! Commented Jan 6, 2016 at 22:23
  • My problem is a bit different. I dont have only a code block where I want syntax highlighting but HTML elements combined with code elements. The solution from the possible duplicate works only for the content of exactly one code element ... imho. Commented Jan 6, 2016 at 22:37

1 Answer 1

1

I fixed my problem by adding syntax highlighting on the server side (because I am doing markdown translation also on server side). I'm using nodejs with expressjs framework as backend.

When fetching my activities I activate highlightjs by a query param (f.e. GET /activities?hljs=true). For each activity I call following function (which is not yet perfectly clean code but it works):

var cheerio = require('cheerio');
var hljs = require('highlight.js');

// ... express routes ...

var highlightPreCodeElements = function (htmlText) {
  var $ = cheerio.load(htmlText);

   $('pre code').each(function(i, block) {
    if ($(this).attr('class') && $(this).attr('class').slice(0, 4) === 'lang') {
      var indexOfMinus = $(this).attr('class').indexOf('-');
      var language = $(this).attr('class').substr(indexOfMinus + 1);
      $(this).html(hljs.highlight(language, $(this).text()).value);
    }
  });

  return $.html();
};

As you can see I am using cheerio (npm install cheerio) for jQuery-API in nodejs and highlight.js (npm install highlight.js).

On the client side I only reference the highlightjs style sheets and thats it.

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.