Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created August 15, 2012 00:00
Show Gist options
  • Save vojtajina/3354046 to your computer and use it in GitHub Desktop.
Save vojtajina/3354046 to your computer and use it in GitHub Desktop.
AngularJS: load all templates in one file
<script type="text/ng-template" id="one.html">
<div>This is first template</div>
</script>
<script type="text/ng-template" id="two.html">
<div>This is second template</div>
</script>
var app = angular.module('test', []);
// HACK: we ask for $injector instead of $compile, to avoid circular dep
app.factory('$templateCache', function($cacheFactory, $http, $injector) {
var cache = $cacheFactory('templates');
var allTplPromise;
return {
get: function(url) {
var fromCache = cache.get(url);
// already have required template in the cache
if (fromCache) {
return fromCache;
}
// first template request ever - get the all tpl file
if (!allTplPromise) {
allTplPromise = $http.get('all-templates.html').then(function(response) {
// compile the response, which will put stuff into the cache
$injector.get('$compile')(response.data);
return response;
});
}
// return the all-tpl promise to all template requests
return allTplPromise.then(function(response) {
return {
status: response.status,
data: cache.get(url)
};
});
},
put: function(key, value) {
cache.put(key, value);
}
};
});
app.config(function($routeProvider) {
$routeProvider.when('/one', {templateUrl: 'one.html'});
$routeProvider.when('/two', {templateUrl: 'two.html'});
});
<!DOCTYPE html>
<html ng-app="test">
<head>
<title>Loading all templates in one file...</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script type="text/javascript" src="fakeTemplateCache.js"></script>
</head>
<body>
<a href="#/one">one</a> | <a href="#/two">two</a>
<div ng-view></div>
</body>
</html>
@Tomas2F
Copy link

Tomas2F commented May 16, 2013

How's this performace wise? Is there any performace difference between this and actually putting all the ng-script inside the script you initally load?

@yogeshgadge
Copy link

Good thinking about performance and programming model where the architectural/design constructs like caching would be taken care by the framework. However this is not in the AngularJS core yet..I understand.

But I am against combining whether at build time or otherwise. Here is a reason why...first it is better if the templates are versioned in VCS..... think about large dev teams and releases...second is the delivery aspect and browser caching perspective....imagine 100s of templates.....sorry but we need a better solution.....will post a gist soon.

@tb01923
Copy link

tb01923 commented Oct 6, 2013

Will this solution work with templates referenced by directives? I am struggling with that now...

@astik
Copy link

astik commented Nov 4, 2013

@Thomas2F sometimes, you don't need (nor want) to load all partials for a specific user. Maybe there are too much partials, maybe some partials won't be needed for the user.
For example, you may have a big application with different universe (lets keep it simple with only front and back-office). A simple user will load only the front part ; an admin user will load all the part he needs when it is needed (lazy loading).

@astik
Copy link

astik commented Nov 4, 2013

@yogeshgadge there is no incompatibility with VCS =)
Indeed, having all partials into a single HTML file (like Vojta's example) is no go for me either. That is why my approach is more modular.

@astik
Copy link

astik commented Nov 4, 2013

@tb01923 yes it does work for directives too.
In fact, it is working with any mechanism that use the $templateCache service (that means, directive, ng-include, ng-view, ...).

@astik
Copy link

astik commented Nov 4, 2013

For those who are interested, I finally finished my extension to take care of this performance feature :

-> https://github.com/astik/grunt-angular-combine : it is a grunt plugin that merge partials file. You can merge all your partials int a single HTML files (like Vojta's example) to in as many module as you want (like my approach).

-> https://github.com/astik/angular-combine : it is an angular module (you'll need to add it to your application) that decorate the $templateCache (like in my previous post). A service is exposed for configuration (as we cannot decorate a provider, as far as I know).

@unbalanced
Copy link

Hey guys, awesome work!

when this code run:

$injector.get('$compile')(response.data);

Are the "internal" templates with in the combined template file pushed into $templateCache service somehow?
I assume they are not, and thus i don't understand how a directive can use an internal template from within the combined template file that we pre-fetched earlier.

Many thanks.

@astik
Copy link

astik commented Dec 12, 2013

Yes.
All internal templates within the combined template file will be pushed into $templateCache once compiled.

@the-simian
Copy link

I really appreciate this example and discussion.

@tdg5
Copy link

tdg5 commented Feb 3, 2014

I wrote up a few tests for this if anyone is interested. This my first spec, so comments are welcome. https://gist.github.com/tdg5/8783501

@veerendrakumar-github
Copy link

I merged all html files into single html file and i include inside app.js file but again its loading that single file and also all html files. plz give correct way to load only merge.html alone with result from test1,test2.html files

see the link i posted: http://plnkr.co/edit/3miUeU2EhS4syZhvrGey?p=preview

plz give correct way to load only merge.html alone but not all html files

@malaikuangren
Copy link

hi vojtajina, your example is very good . and also work around for me . But I have some questions . hope you can help to review them.

I found actually the angularjs(1.2.16) already has a service named "$templateCache" which is implemented by $provide.
and I found the fakeTemplateCache.js is behind the angular js .
So it seems the factory "$templateCache" in your example overwrite the implement of original provider "$templateCache". right ?

@manikantag
Copy link

For any one struggling for AngularJS 1.3 compatibility, esp. with the below error, here is the fix.

I've similar module in my project. It is working fine until I upgrade to AngularJS 1.3, after which the script is throwing below error:

TypeError: undefined is not a function
    at defaultHttpResponseTransform (http://localhost:9080/js/lib/angular/angular.js:8569:27)
    at http://localhost:9080/js/lib/angular/angular.js:8517:12
    at forEach (http://localhost:9080/js/lib/angular/angular.js:335:20)
    at transformData (http://localhost:9080/js/lib/angular/angular.js:8516:3)
    at transformResponse (http://localhost:9080/js/lib/angular/angular.js:9224:23)
    at processQueue (http://localhost:9080/js/lib/angular/angular.js:12914:27)
    at http://localhost:9080/js/lib/angular/angular.js:12930:27
    at Scope.$eval (http://localhost:9080/js/lib/angular/angular.js:14123:28)
    at Scope.$digest (http://localhost:9080/js/lib/angular/angular.js:13939:31)
    at Scope.$apply (http://localhost:9080/js/lib/angular/angular.js:14227:24)

This could be related to angular/angular.js#2973 (also, report here nervgh/angular-file-upload#272) - not sure though.

Fix for this simple - we need to return headers too from the combinedTplPromise.then function, like below: (I m using astik's version - https://gist.github.com/vojtajina/3354046#comment-814584)

combinedTplPromise.then(function(response) {
    return {
        status: response.status,
        data: origGetMethod(url),
        headers: response.headers
        };
});

Hope this will be useful to someone else. Same fix is reported here too: astik/angular-combine#2

@manikantag
Copy link

Also, I recommend https://github.com/astik/angular-combine which extends this technique to support multiple combined template files.

@JesseBuesking
Copy link

@manikantag I just ran into the same issue and your solution fixed my problem, so thank you!

One thing I'm wondering though, is whether it'd be safer to do this instead:

combinedTplPromise.then(function(response) {
    response.data = origGetMethod(url);
    return response;
});

This way any future changes to the response object will make it through safely, as we're really only caching the response data. Thoughts?

@astik
Copy link

astik commented May 23, 2015

@tdg5, thanks for the testing bootstrap, it motivates me to add some on my plugin ; I know it's been a while, but, better late than never =)
Anyway, just for information, https://github.com/astik/angular-combine is still alive as of its counterpart https://github.com/astik/grunt-angular-combine.
Feel free to participate =)

@mikeulkeul
Copy link

Thank you for the code!
I just patch it in case partial.tmpl doesn't exist (like in a environment development)

app.factory('$templateCache', function($cacheFactory, $http, $injector) {
    var cache = $cacheFactory('templates');
    var allTplPromise;

    return {
        get: function(url) {
            var fromCache = cache.get(url);

            // already have required template in the cache
            if (fromCache) {
                return fromCache;
            }

            // first template request ever - get the all tpl file
            if (!allTplPromise) {
                allTplPromise = $http.get('partial.tmpl').then(function(response) {
                    // compile the response, which will put stuff into the cache
                    $injector.get('$compile')(response.data);
                    return response;
                });
            }

            // return the all-tpl promise to all template requests
            return allTplPromise.then(function(response) {
                return {
                    status: response.status,
                    data: cache.get(url)
                };
            }).catch(function(){
                return $http.get(url).then(function(response) {
                    $injector.get('$compile')(response.data);
                    return response;
                });
            });

        },

        put: function(key, value) {
            cache.put(key, value);
        }
    };
});

@ebinmanuval
Copy link

ebinmanuval commented Aug 25, 2016

is there any problem if i use this code

app.run(function($http, $templateCache){

    $http.get('all-templates.html').then(function(response) {

        var $html = $('<div />',{html:response.data});
        var elements=$html.find('script');
        angular.forEach(elements,function(element){
            $templateCache.put(element.id,element.innerHTML);

        });

    });

});

@redgeoff
Copy link

Awesome!!

@patilkomal
Copy link

patilkomal commented Nov 21, 2017

hello guys...i am facing with one problem in ionic2...i want linked index.html page with second page of app..how to do it???
In actual have an svg iamge n second page of ionic2 which should be fill with color on click, by accessing index.html file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment