How to Cache Angular scope - javascript

What is the best technique to cache Angular Scope from last browser session to a newly loaded one?
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?

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:
ngStorage: Local and session storage the angular way
angular-local-storage: Simple local storage with a cookies fallback
$cookies: Angular provided service wrapping cookies access
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/session storage, cookies, or a server-side solution.
$cookies
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');
}]);
Don't use cookies to store extensive data and limit this to data which should be sent on every request, like a authentication token.
ngStorage
An AngularJS module that makes Web Storage working in the Angular Way.
Contains two services: $localStorage and $sessionStorage.
bower install ngstorage
Pass $localStorage (or $sessionStorage) by reference to a hook
under $scope in plain ol' JavaScript:
$scope.$storage = $localStorage;
And use it like you-already-know:
<body ng-controller="Ctrl">
<button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>
Optionally, specify default values using the $default() method:
$scope.$storage = $localStorage.$default({
counter: 42
});
With this setup, changes will be automatically sync'd between
$scope.$storage, $localStorage, and localStorage - even across
different browser tabs!
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.setPrefix('demoPrefix');
// localStorageServiceProvider.setStorageCookieDomain('example.com');
// localStorageServiceProvider.setStorageType('sessionStorage');
})
.controller('DemoCtrl',
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
How to access cookies in AngularJS
How to set expiration date for cookie in AngularJS
How to persist data in AngularJS

Related

accessing stored locale from angular-translate FileStorage

I am using angular-translate with LocalStorage and it works very well. Locales are cached or stored on local disk. When the browser is closed and re-launched the chosen locale is persisted.
My question is how can I access that cached or stored locale that's on disk in one of my controllers? To better explain here's the workflow that is not working:
1. Launch browser to localhost and can see the site with previously chosen locale
2. Attempt to access the current locale from either the
2.1 $translate.proposedLanguage()
2.2 tmhDynamicLocale
3. Both are undefined -- even though the correct language is shown
4. Select language choice once more
5. current locale from both the above is now correct
Here is the JSFiddle for the module and locale service. Not runnable code. Just an example of the code I'm using
I am trying to access currentLocale but it is undefined until the user makes a selection (again). I know it's stored somewhere since the original selection is persisted after browser exit.
After about 2 hours in a rabbit whole of API docs and angular-translate-* sources files I found that I can pass $translateLocalStorage to my controller and then call $translateLocalStorage.get() which will return that cached localId.
That method pulls the localId from `$window.localStorage.getItem. That code is
get: function (name) {
if(!langKey) {
langKey = $window.localStorage.getItem(name);
}
return langKey;
}
So all you would need to do is:
angular.module('myModule')
.controller('QueryController', function($scope, es, $translateLocalStorage) {
$scope.show_results = function(results) {
var currentLocale = $translateLocalStorgae.get();
}
});

where to store global data in angular JS?

In angular Js i am trying to store user data such as profile name that should exist in most of routes is it a good practice to store them in the $rootScope. IF not where should i store them.
If you use a service it's everywhere available and if it should be persistent over page reloads and so on, then you can store the data in local storage or a cookie etc. and access it with your service on load.
angular.module('app')
.factory('UserService', ['SessionService', function(SessionService) {
SessionService.load();
var user = SessionService.getUser();
var service = {
setUser: function(u){ user = u; },
getUser: function(){ return user; }
};
return service;
}])
.controller('DemoCtrl', ['$scope', 'UserService', function($scope, UserService){
$scope.user = UserService.getUser();
}]);
I'm new to angular myself but the route I'm taking is to write a service. You could have a service that stores the user profile data. I would maybe put a method on the service to load the profile data and then store it locally in the service. You could then get this information via a getter method.

Is it possible to grab the cookie from the view in AngularJS?

I was just wondering if it's possible, I was looking to grab the cookie to see if it's an admin user, and I'm not sure how to do that.
you can use $cookies for reading and writing into cookies...
example from angular docs
function ExampleController($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.myFavorite;
// Setting a cookie
$cookies.myFavorite = 'oatmeal';
}
UPDATE
you should add angular-cookies.js script and inject ngCookies into you application module
angular.module('app', ['ngCookies']);

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

AngularJS - Broadcasting across controllers

Am trying a scenario where i Login, and, on success, want to store that LoginID and pass it to all other controllers for navigation/user management. Similar to a global variable set up, store once use everywhere concept.
Been using angularjs shared Services technique but its not picking the braodcaster LoginID in other controllers.
High level details:
1) Login HTML calls Login Controller from where i call back end server for user authentication
2) On success, broadcasted LoginID via shared service
3) from Login HTML, page navigates to OrderMenu Html and calls OrderMenu controller where am trying to fetch the User id which was broadcasted via the shared service.
4) but in the Order Menu controller the UserID shown is the initialized value i.e looks like app.factory is being called again and initializing the Broadcasted value.
I want to stop the reloading of app.factory. Looks like am missing something here.Any thoughts would be really helpful here.
Here is a quick implemention example of what you described.
And it seems to be working.
http://plnkr.co/edit/SPAB4W
My service is defined as follows:
app.factory('UserAuth', function() {
return {
userId: 'unknown',
authenticate: function( name ) {
// do server side authentication here...
this.userId = 'authenticatedUserId_Of_' + name;
}
};
});
In this example, when second controller (OrderCtrl) is getting called,
UserAuth.userId does not get re-initialized
and keeps the obtained userId of what authentication gives.
You may want to share your code.

Categories