LoginSignup
8
9

More than 5 years have passed since last update.

AngularでMarkdownを表示する

Last updated at Posted at 2014-07-11

最近のAngularはサニタイズ周りが強化されていて、filterでは実装が難しそう(ムリ?)だったので、directive版です。Vue.jsのデモみたいにできると、本当は直観的なんですが...

構成要素

AngularがCommonJSになっていないためクセがありますが、Debowerifyを使うとBrowserifyできるようになります。

Bower経由

  • angular

npm経由

  • browserify
  • debowerify: Browserifyのトランスフォーム
  • coffeeify: Browserifyのトランスフォーム
  • marked: Markdownの変換エンジン

実装

こんな感じになりました。directiveの定義は5行ほど。AngularとCoffeeScriptは相性が良いですね。

index.coffee

require 'angular'

angular.module 'app', []
.directive 'marked', require './marked'

marked.coffee

短いのでファイルを分けるまでもないのですが、一応再利用しやすいように。

marked = require 'marked'

module.exports = ->
  restrict: 'A'
  link: (scope, element, attrs) ->
    element.html marked element.text()

index.html

Markdownを使いたいタグにmarkedという独自属性を付けています。Markdownは直接書いてもOKですが、この例では別ファイルからインクルード。

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Markdown</title>
  </head>
  <body>
    <section marked ng-include="'sample.md'"></section>
    <script src="index.js"></script>
  </body>
</html>

sample.md

# Sample Markdown

- Angular.js
- Browserify
- Debowerify
- Coffeeify
- Marked
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9