Friday, May 11, 2012

Custom Components: Part 1

Custom Components: Part 1

In this video, John Lindquist walks through adding new tags to the browser using an AngularJS directive.  Here, he uses the Showdown.js library to create a <markdown> tag that lets you write Markdown instead of HTML.

Key Takeaways

  • AngularJS directives transform HTML as you direct.
  • You can use directives to define your own elements, attributes, classes, or comment types.
  • Using the directive's linking function is one method that lets you specify the replacement content.
  • AngularJS plays very well with other libraries.

Source (edit on JSFiddle)

html

<div ng-app="myApp">
    <markdown>
# Hello World!
- Zeppelin
- That guy
- Kronos
    </markdown>
</div>​​​​​​​​​​​​​​​​

services.js

angular.module('myApp'[]).directive('markdown'function({
    var converter new Showdown.converter();
 ​   return {
        restrict'E',
        linkfunction(scopeelementattrs{
            var htmlText converter.makeHtml(element.text());
            element.html(htmlText);
        }
    }
});

6 comments:

  1. but this doesnt work with ng-model... it just renders a placeholder, like {{ post.title }}

    ReplyDelete
  2. @Vitaly you can watch ngModel and require it by using the "require" attribute of the directive. I create a method called "render" which does the highlight, then I watch attrs['ngModel'] and call that method.

    Here's a fiddle that shows you how it works: http://jsfiddle.net/8bENp/66/

    ReplyDelete
  3. If you copy, there is a Zero-width space(&#8203) before the return statement that will break the code. Very hard to find something like that if you dont know the problem.

    ReplyDelete
  4. Ah...apologies. It's difficult to to control the final HTML output here in Blogger. Sorry about that!

    The JSFiddle is certainly a better route.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete

Note: Only a member of this blog may post a comment.