CaribouCode
CaribouCode

Reputation: 14398

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?

Upvotes: 7

Views: 12209

Answers (2)

Igor Pantović
Igor Pantović

Reputation: 9246

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>

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245389

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.

Upvotes: 14

Related Questions