最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Markdown to HTML in AngularJS - Stack Overflow

programmeradmin0浏览0评论

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]() sit amet, consectetur adipiscing elit. Integer iaculis turpis ut enim eleifend venenatis. Proin nec ante quis nulla porta finibus. Suspendisse at [mauris]() 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?

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?

Share Improve this question asked Apr 24, 2015 at 14:31 CaribouCodeCaribouCode 14.4k33 gold badges111 silver badges183 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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.

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>
发布评论

评论列表(0)

  1. 暂无评论