Combining ng-bind-html with highlight.js

I am currently working on implementing syntax highlighting for all code elements within dynamically added HTML content that will be appended to the existing page using 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 typically contains content 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>

Currently, the setup is functional but lacking syntax highlighting. To address this issue, I have implemented highlightjs and angular-highlightjs. The modification made was changing

<div ng-bind-html="activity.text">
to
<div hljs ng-bind-html="activity.text">
. However, there is a challenge encountered with how ng-bind-html and hljs directives interact; the expected syntax highlighting is not applied specifically to code tags (pre code), but rather to the entire HTML content.

Seeking advice on alternative approaches to achieve syntax highlighting for dynamically loaded content.

Answer №1

After encountering an issue, I successfully resolved it by implementing syntax highlighting on the server side, given that markdown translation was also being performed on the server. My backend setup comprises nodejs with expressjs framework.

To enable highlightjs when fetching activities, I included a query parameter (e.g., GET /activities?hljs=true). For each activity, I utilized the following function (which, although not entirely refined, proved effective):

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();
};

In this implementation, I leveraged cheerio (npm install cheerio) for jQuery-API functionalities in nodejs and highlight.js (npm install highlight.js).

As for the client side, only the reference to highlightjs style sheets was necessary for proper display.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing a function within a React functional component using jest.spyOn with React Testing Library can be accomplished with the following steps:

I'm currently working on a React component and I'm facing an issue with unit testing using React Testing Library. Specifically, I'm having trouble testing the handleClick function of the TestComponent using jest.spyOn(). Can anyone provide s ...

Connecting UserIDs with Embedded Documents in Mongoose

My goal is to connect individuals with each other by embedding a Match document in the user's matches array. This is my User Model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Match = new Schema({ with: ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

Navigate within a JSON object using an identifier to extract a particular value associated with that identifier

Exploring a JSON object containing nested arrays and objects. The label value acts as the identifier to find and return its corresponding level's metrics value. If the label is located at the second level, retrieve and return the metrics from that lev ...

Having troubles retrieving the selected option with AngularJS

Looking to retrieve the chosen option from a select tag using Angular JS. Currently, the attribute value is returned as "1, 2..", but I require it to be "one, two.. when the select tag is changed. Below is a snippet of my code: JS var app = angular.modu ...

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

The checkbox is displayed as selected after being clicked in conjunction with another checkbox

In the tree structure, there are checkboxes that behave strangely when clicked. I have already read a similar discussion here. The problem I am encountering is that when I click on an item, it gets checked but the console does not show it as checked immed ...

The default selection in res.format is not being properly recognized

When I make a request with the accept header set as "application/json, text/javascript, */*; q=0.01", the response is always in HTML format instead of the default format specified. It seems like something is missing here. Given that the header does not spe ...

Encountering a ng-select2 Error with Angular version 4.1.3

I have recently installed the ng-select2 package, but I encountered an error when trying to compile my code using 'ng serve'. Node version: 8.10.0 NPM version: 6.0.0 Another list item Operating System: Windows 7 ERROR in d:/PATH-TO-PROJECT-F ...

Implementing template loading on page load with state in AngularJS

When my application loads, I want the nested view list-patents.htm to be displayed. The main navigation is on my index.htm, featuring two nav items: transactions and patents. If you click on patents, two sub-menu items will appear: list patents and add p ...

Using JavaScript, append a hidden input field in Yii2 and retrieve it from the controller

Seeking assistance as a newcomer to yii2. I'm looking for help in resolving an issue that has arisen. I'm attempting to add a hidden input field to my form using JavaScript (not linked to a model). Subsequently, when I submit the form, I want to ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Using the same bone structure to share skeletons among SkinnedMeshes in Three.JS

I've been grappling with the challenge of incorporating and removing clothing pieces to an existing skeleton (Clothing meshes and body meshes should share skeleton) but I always seem to encounter strange results. All the clothing items that I intend ...

Adding static files to your HTML page with node.js

This is not a question about using express.static() In my application, I have multiple pages that share the same JS and CSS dependencies. Instead of adding <script> or <link> tags to every single page, I'm looking for a way to include the ...

Generating a fresh document in MongoDB using Mongoose, complete with references and assigned ObjectIDs

I've been attempting to use the mongoose create function in order to generate a new document with references, but I'm encountering an error when trying to provide objectIds for those refs. Despite my efforts to find a solution, I have been unsucc ...

Refresh information in AngularJS controller

I am currently working on a straightforward AngularJS script that is designed to retrieve data from a socket.io event and then integrate it into the ng template. Below is the JavaScript code I have written for this purpose: // Socket.io logic: var message ...

Troubleshooting: Issue with NodeJS Mongoose async function not returning value

Having an ongoing issue with retrieving a value from my async functions in the mongoose service. The problem persists as it consistently returns undefined, leaving me puzzled about what's going wrong. Being new to this area, any assistance would be gr ...