Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown to HTML in AngularJS

I'm using Contentful API to pull in some content. It arrives as a json object to my Node server, which passes it to my Angular frontend. Content in the json object contains unprocessed markdown text.

For example the Angular call might look like this:

var id = "asdf76f7g68sd7g";
$http.get("/api/article/" + id).then(function(res){
  $scope.article = res.data;
});

The object for $scope.article would then look similar to this:

$scope.article = {
  title: "Some title",
  content: "Lorem ipsum [dolor](http://google.com) sit amet, consectetur adipiscing elit. Integer iaculis turpis ut enim eleifend venenatis. Proin nec ante quis nulla porta finibus. Suspendisse at [mauris](http://google.com) nisi."
};

In my HTML I would then display the content like so:

<p>{{article.title}}</p>
<p>{{article.content}}</p>

The problem here is the markdown is not converted to HTML and renders as you see it in the object. How can I convert any markdown to HTML and render the results?

like image 605
CaribouCode Avatar asked Apr 24 '15 14:04

CaribouCode


2 Answers

The easiest way would be to find an Angular Directive that can render Markdown.

A simple Google Search revealed https://github.com/btford/angular-markdown-directive. That should solve your problem.

like image 180
Justin Niessner Avatar answered Oct 22 '22 10:10

Justin Niessner


You can use a library like markdown-js. And then just process it when fetched (note you have to inject $sce because angular doesn't allow printing out HTML because of security concerns by default):

var id = "asdf76f7g68sd7g";
$http.get("/api/article/" + id).then(function(res){
  var article = res.data;
  article.content = $sce.trustAsHtml(markdown.toHTML(article.content));
  $scope.article = article;
});

And in your view:

<div ng-bind-html="article.content"></div>
like image 41
Igor Pantović Avatar answered Oct 22 '22 09:10

Igor Pantović