Using PrismJs with AngularJs
In a project I’m working on I need to display code snippets. I found PrismJs library, which is lightweight and cover a lot of languages. The application is based on AngularJs, and code snippets are displayed after having been read from an API and PrimsJs is run before code is injected in the template, when used as the documentation said, so highlighting doesn’t work. The problem can be tackled down with the creation of a directive. Here is the code :
angular.module('Prism', []).
directive('prism', [function() {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
element.ready(function() {
Prism.highlightElement(element[0]);
});
}
}
}]
);
For each HTML element marked with the prism attribute we wait that the inner DOM is fully loaded, using the ready function, and then trigger Prism highlighting on it.
<pre>
<code class="language-markup" prism>
{{ snippet }}
</code>
</pre>
Here is the Gist !
- Improve your automated testing : You will learn how to fix your tests and make them pass from things that slow you down to things that save you time. This is a self-paced video course in French.
- Helping your teams: I help software teams deliver better software sooner. We'll work on technical issues with code, test or architecture, or the process and organization depending on your needs. Book a free call where we'll discuss how things are going on your side and how I can help you.
- Deliver a talk in your organization: I have a few talks that I enjoy presenting, and I can share with your organization(meetup, conference, company, BBL). If you feel that we could work on a new topic together, let's discuss that.