Define your own HTML Element with AngularJS


Testing is important to me so I created a page on my blog to keep track of JavaScript testing tools. I was interested in knowing which are the most popular ones so I decided to track how many people starred each one on GitHub. The number of stars changes over time, however, so that posed a challenge of how to update the page dynamically.

I decided to create an elegant solution leveraging AngularJS's abililty to define new HTML elements (AngularJS calls these directives). I defined a new HTML element for displaying the number of stars in a GitHub repository:

<GitHubStars repository="NodeGuy/ServerDate"></GitHubStars>

It takes a single attribute named repository. The above example specifies the repository for my ServerDate library.

AngularJS's magic transforms the GitHubStars element into a link element which both points to the GitHub repository and shows the current star count, like this:

ServerDate has a count of stars right now.

But how does it count the current number of stars? It sends a query to GitHub's API:

The last thing I needed to do was to embed the above code into the blog article page. I'm using the Ghost blogging platform (implemented with Node.js, yay!) and it allows direct embedding of JavaScript but unfortunately it decided that some of my JavaScript was written in Markdown and performed unwanted interpretation. To include clean JavaScript code I'd have to host it somewhere else. Where is an easy, lightweight place to host a snippet of code? Why, in a gist on GitHub of course! But wait, gists are downloaded with the Content-Type header of text/plain, not the application/javascript we need for execution in the browser. Fortunately, Ryan Grove completed the missing link with his clever RawGit service, adding the correct Content-type header to our gist.

Now all of the star counts are updated in real time whenever the page is loaded. Go check it out:

View or Post Comments