Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive to parse and replace custom element contents

I would like to create a simple markdown directive that accepts some content within the element, parses it and replaces it with html.

So this:

<markdown>#Heading</markdown>

or this (where $scope.heading = '#Heading';)

<markdown>{{heading}}</markdown>

Becomes this:

<h1>Heading</h1>

My directive so far (obviously not complete!):

.directive('markdown', function () {
    return {
        restrict: 'E',
        replace: true,
        link: function ($scope, $element, $attrs) {
            // Grab contents
                var contents = /* How do I do this? */

                var newContents = Markdowner.transform(contents);

                // Replace <markdown> element with newContents
                /* How do I do this? */
        }
    }
})

I'm unsure of how to grab the contents of the directive? Would I need to compile it?!

Parsing Markdown is just an example

like image 770
Greg Avatar asked Jan 06 '14 14:01

Greg


1 Answers

Here you go!

Working Demo

app.directive('markdown', function() {
  return {
    restrict: 'E',
    transclude: true,
    compile: function(elem) {
      elem.replaceWith(Markdowner.transform(elem.html()));
    }
  }
});
like image 68
jessegavin Avatar answered Nov 15 '22 22:11

jessegavin