AngularJs inside Jade templates

How to write AngularJS code inside server-side Jade templates.

I love AngularJs MVC, but I hate writing HTML markup code. Lately I have been using Jade to minimize the amount of markup in my static pages. The question arises: can AngularJs be used easily inside Jade templates?

Background

I am using a Nodejs-based Express server to power next-update-stats app. It is simple server keeping anonymous package version upgrade success information. It is meant to work with next-update to quickly check if updating a dependency to latest version breaks your package. The next-update-stats is a simple server keeping results and serving as a home page for the project. I wanted to add interactive search and data visualization to the home page. For example, a visitor could enter package name lodash to see if upgrading from 1.0.0 to 2.0.0 is usually successful or not.

Site index template

The main page is generated from layout.jade, I added a script tag to load the latest stable version of Angular from CDN and my specific script locally. The HTML element gets ng-app attribute to bootstrap the AngularJs application.

1
2
3
4
5
6
7
doctype html
html(ng-app='next-update-stats')
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js')
script(src='javascripts/next-update-stats.js')

Then I added Express development setting to prettify the rendered HTML, otherwise it was hard to debug the generated page in the browser, see app.js

1
2
app.set('view engine', 'jade');
app.configure('development', function () { app.locals.pretty = true; });

I also added search field and button to a div controlled by the application, see index.jade

1
2
3
4
5
6
7
8
9
10
11
div(ng-controller="next-update-stats-controller")
p See global upgrade statistics for a package
input(type="text", placeholder="package name", ng-model="packageName"
title="Enter package module to see update statistics")
button.btn(ng-click="loadStats()" title="click to search") Load
ul
li(ng-repeat="update in updates").
{{update.name}} {{update.from}} -> {{update.to}}
{{update.probability}}%
{{update.success}} successful
{{update.failure}} failed

The code worked right away, there were no issues with double quotes or Jade trying to process handlebar variables, like {{update.name}}.

I will investigate using Jade templates as the primary AngularJs templates in the future posts.

Update

I have added Jade to JavaScript support to grunt-html2js allowing one to use Jade for angular directive template. See this blog post.