AngularJS putting a template in the $templateCache

Posted by ryansouthgate on 20 Jan 2016

This is a quick post about getting a template in the $templateCache.

A SPA (Single Page Application) I’m building at work, consists of 4 “views”. We expect the users to be on this page for a good while (anything from 5 mins upwards). The threat of losing internet connectivity is a real one and would render our application useless (we regularly call out to a JSON API to update results on the user’s request).

I’ve written an Angular Module for Error Handling so I write it once and can reuse it when I need it again (a good type of lazy) - I will be needing it again.

The service looks like this:

And the html:

I call the ErrorService.ShowError(info) when I encounter an error in one of the calls to the JSON API - the reject bit of promises. The Info is just an object which I can populate with various properties to help show information about the error. In the example I’ve just included a Message Property and bound that to the screen.

The cool part of this error module is $templateRequest(templateUrl); this runs our template through Angular’s template request system - on request, Angular realises that it doesn’t have that template (it checks the cache first) - so it goes and fetches it and puts it in the cache for later.

Doing this at app start-up (it’s a service so it’s initialised once and only once) means that we get the template when we know (or are extremely likely) to have an internet connection - as the page has just been loaded from the server.

An alternative to making this request would be to inline the template definition inside the page’s html mark-up using the script directive, however in my situation I don’t have full control of the page we are being rendered in to - so I had to work with the $templateRequest directly.

There is room for further work - we could extend this service to take in the templateUrl (then we can specify different html and controllers).



comments powered by Disqus