AHJ AHJ - 1 year ago 143
AngularJS Question

How to Cache Angular scope

What is the best technic to cache Angular Scope from last browser session to a newly loaded?

Is that possible?

Including to control the next time to create a cache of the complete scope?

And override the loaded cached scope, when new data is loaded from the back-end?

Answer Source

This is more related to how to cache data in the browser using javascript.

There are some solutions you can look into for angular specifically:

Angular services can be used to share the scope between routes within the same session. But if you close the browser, you'll need one of local storage, cookies, or a server-side solution.


Cookies is a straightforward key-value storage. Easy to use for a quick way to save data.

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
    // Retrieving a cookie
    var favoriteCookie = $cookies.get('myFavorite');
    // Setting a cookie
    $cookies.put('myFavorite', 'oatmeal');

local storage demo

The angular-local-storage module provides multiple ways to store your data. It's feature rich and provides advanced options and customisation.

window.angular.module('demoModule', ['LocalStorageModule'])
    .config(function(localStorageServiceProvider) {
        // localStorageServiceProvider.setStorageCookieDomain('example.com');
        // localStorageServiceProvider.setStorageType('sessionStorage');
        function($scope, localStorageService) {
            $scope.localStorageDemo = localStorageService.get('localStorageDemo');

            $scope.$watch('localStorageDemo', function(value) {
                localStorageService.set('localStorageDemo', value);
                $scope.localStorageDemoValue = localStorageService.get('localStorageDemo');

            $scope.storageType = 'Local storage';

            if (localStorageService.getStorageType().indexOf('session') >= 0) {
                $scope.storageType = 'Session storage';

            if (!localStorageService.isSupported) {
                $scope.storageType = 'Cookie';

            $scope.$watch(function() {
                return localStorageService.get('localStorageDemo');
            }, function(value) {
                $scope.localStorageDemo = value;

            $scope.clearAll = localStorageService.clearAll;

Additional information

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download