author thumb

Software Developer

Creating a markdown blog using AngularJS

In this post i’ll show you how to create a blog engine to read Markdown files just using AngularJS :) So let’s get started.

First of all, you will need to include the showdown script in your app. You can use this CDN

<script src="http://cdnjs.cloudflare.com/ajax/libs/showdown/0.3.1/showdown.min.js"></script>

So, how this will work? Well, its very simple:

  • To get started we will list all posts in a file named posts.json. This file will have some basic information from the post, like title, the slug and the link to the markdown file. Your file must look like this:
[
  {
    "title": "Creating a markdown blog using AngularJS",
    "slug": "creating-a-markdown-blog-using-angular-js",
    "file": "creating-a-markdown-blog-using-angular-js.md",
    "tags": [
      {"title" : "Javascript"},
      {"title": "AngularJS"}
    ]
  }
]
  • We will read this information using the $http service from angular. I created a service to help us in this task
'use strict';
angular.module('blogApp')
  .factory('Posts', function($http) {
    return{
      getPosts: function(callback){
        $http.get('/posts/posts.json').success(callback);
      }
    }
  });

You can use this service in your controller like this:

angular.module('myApp')
  .controller('MainCtrl', function ($scope, Posts) {
    Posts.getPosts(function(data){
      $scope.posts = data;
    })
  });
  • Now we have to loop this posts in our blog
< div ng-repeat="post in posts">
	< h2> \{\{ post.title }} < /h2>
  < div markdown link="">< /div>
< /div>
  • Now the final part ! We’ll use a directive to convert our markdown to html
// app/scripts/directives/markdown.js
'use strict';
angular.module('myApp')
  .directive('markdown', function ($http) {
    var converter = new Showdown.converter();
    return {
      restrict: 'A',
      scope: { link:'@' },
      link: function (scope, element, attrs) {
        attrs.$observe('link',function(link){
            $http.get('/posts/files/' + link).success(function(response){
              var htmlText = converter.makeHtml(response);
              element.html(htmlText);
            });
        });
      }
    };
  });

This directive is very simple. She grabs the markdown file path from each post, make a http request and convert it to HTML using the showdown script.

And this is it!

You can write new posts and store in markdown files at app/posts/files and list this posts in the app/posts/posts.json file.

author thumb

Hugo Dias

Desenvolvedor Back-end & Front-end, Desenvolvimento Android e IOS, HTML5, CSS3 e JavaScript