The main part of the answer is the $templateCache. An extract:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
Any of the html templates, can be moved to the $templateCache
, and the rest of our application will act as expected (no other changes required)
local-storage as a cache
In case, that we would like to keep the template on the client, we can use the local storage as well. This angular-local-storage extension would simplify lot of stuff.
So, let's adjust the run()
to
- observe the
local-storage
, if we do not already have the template on the client
- issue the request to load the latest, if needed...
- put it into the caches (
local-storage
and $templateCache
)
The adjusted code
.run([ 'localStorageService','$templateCache','$http',
function myAppConfig(localStorageService , $templateCache , $http) {
// The clearAll() should be called if we need clear the local storage
// the best is by checking the previously stored value, e.g. version constant
// localStorageService.clearAll();
var templateKey = "TheRealPathToTheTemplate.tpl.html";
// is it already loaded?
var template = localStorageService.get(templateKey);
// load the template and cache it
if (!template) {
$http.get(templateKey)
.then(function(response) {
// template loaded from the server
template = response.data;
localStorageService.add(templateKey, template);
$templateCache.put(templateKey, template);
});
} else {
// inject the template
$templateCache.put(templateKey, template);
}
}])
So, this way, we do profit from the local-storage
. It is filled with the "template" from the server, kept there... and therefore not loaded next time.
NOTE: Very important is also to inject some version
key/value and check it. If the Local storage is out-dated... all templates must be reloaded.