!geek

Code, learn & share

Printing external html templates using AngularJS

Use case

In Bahmni EMR we needed to support customizable html templates for printing patient regisatrtion card and other printable documents. We needed a print API which looks like

1
2
3
4
5
//Contract
printer.print(templateUrl, data)

//This would called on clicking the print button
printer.print('/config/registrationCardTempate.html', {patient: {name: 'Ram Kumar', dateOfBirth: '1978-08-23', gender: 'M'}})

Waiting for AngularJS digest cycle

The million dollar question most of the AngularJS users(devs) end up asking is

  • How to wait for angular digest cycle to be completed? or in simple terms
  • How to wait for browser to complete rendering the view with angular bindings?

Printing html with image and css

There are plenty of examples for printing html of an element. Most of them look like this

1
2
3
4
5
6
7
8
9
10
11
12
//The simple soultion but has few problems listed below.
function printHtml(html)
{
    var mywindow = window.open();
    mywindow.document.write('<html><head><title>My App</title>');
    mywindow.document.write('</head><body>');
    mywindow.document.write(html);
    mywindow.document.write('</body></html>');
    mywindow.print();
    mywindow.close();
    return true;
}

The issues with above solution:

Debugging angular ui-router

The ui-router from angular-ui gives power of nested states and multiple named views which is essential for angular apps with non-trivial layout and workflow.

The main problem with angular ui-router is getting the route configurations right in the first time. You start seeing blank pages for misconfigured views. The sad part is these errors are not logged to console. It gets quite frustrating in tracking down the cause.

Introducing f.js

Javascript code is quite verbose when compared to other langauges. One of the features I missed coming from the ruby world is lambdas and the &: sugar.

1
2
3
books.map { |book| => book.title }
# or even better
books.map(&:title)

compare this with javascript code

1
books.map(function(book) { return book.title })