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>
@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