Skip to content

Instantly share code, notes, and snippets.

@colorsocean
Forked from vojtajina/all-templates.html
Created June 22, 2014 19:34
Show Gist options
  • Save colorsocean/c0f1bb1f36e0eb4d28e4 to your computer and use it in GitHub Desktop.
Save colorsocean/c0f1bb1f36e0eb4d28e4 to your computer and use it in GitHub Desktop.

Revisions

  1. @vojtajina vojtajina created this gist Aug 15, 2012.
    7 changes: 7 additions & 0 deletions all-templates.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    <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>
    46 changes: 46 additions & 0 deletions fakeTemplateCache.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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'});
    });
    13 changes: 13 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    <!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>