How to cache corner partial parts?

What is the easiest / most modern way to cache score in angularjs?

Currently, the code looks like this:

$routeProvider.when('/error', {templateUrl: 'partials/error.html', controller: 'ErrorCtrl'});

Where templateUrl is obviously the http path to a single file. On a mobile device, the download time for this file is noticeable, and I would just like to cache everything.

+4
source share
1 answer

The bulk of the answer is $ templateCache . Exposure:

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 migrated to $templateCache, and the rest of our application will act as expected (no other changes are required)

local cache storage

, , . angular-local-storage .

, run()

  • local-storage,
  • , ...
  • (local-storage $templateCache)

.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);
    }

    }])

, , local-storage. "" , ... .

. / version . , .

+7

All Articles