Save information on Client using AngularJS

Today we are implementing exceptionally straightforward case of how to save object value or any information on client side using in AngularJS.There are many options to store information.

In this Blog I am going to give some example on "How to save information on client machine". Now we are implementing a set of example with straightforward case of how to save object value or any information on client side using in AngularJS. In this blog I am giving you many method to save information on client machine which is listed below.
  1. LocalStorage
  2. Sessionstorage
  3. Window storage
  4. Cookies storage
1. LocalStorage - Localstorage is used to store any type of information, data, object. See example on how to set and get value.
  1. // olditem ==Your object value or information    
  2. getitem :-    
  3. localStorage.getItem('history');    
  4. //history is key    
  5. Remove item:-    
  6. $scope.RemoveHistory = function (item,index) {    
  7. var historyData = localStorage.getItem('history');    
  8. var parsedData = JSON.parse(historyData);    
  9. for (i = 0; i < parsedData.length; i++) {    
  10. //check condition (optional)    
  11. if (parsedData[i].UserName === item.UserName && parsedData[i].source === item.source && parsedData[i].destination === item.destination)    
  12. {    
  13. parsedData.splice(i, 1);    
  14. //Remove item using index and set again in same key "history".    
  15. localStorage["history"] = JSON.stringify(parsedData);    
  16. }    
  17. }   
2. Sessionstorage - Using sessionstorage you will store key pair value. See example below.
 
sessionStorage.setItem('key', 'value');
var data = sessionStorage.getItem('key');
 
3. Window storage - Its same as session storage. See example.
 
window.localStorage.setItem("key", Value);
var data=window.localStorage.getItem("UserToken");
 
4. Cookies storage - Once you want use $cookies, firstly inject library in your application. See example below.
  1. angular.module('cookiesExample', ['ngCookies']) .controller('ExampleController', ['$cookies'function($cookies) {  
  2. // Retrieving a cookie  
  3. var favoriteCookie = $cookies.get('myFavorite');  
  4. // Setting a cookie  
  5. $cookies.put('myFavorite', value);  
  6. }]);  
Use $cookiesProvider to change the default behavior of the $cookies service.
 
Note - Don't forget to add respective directive for storage option.best option is localstorage than other.
 
Difference between localStorage ,sessionStorage and Cookies
 
As far as abilities, Cookies just permit you to store strings. sessionStorage and localStorage permit you to store JavaScript primitives yet not Objects or Arrays (it is conceivable to JSON serialize them to store them utilizing the APIs). Session stockpiling will by and large permit you to store any primitives or items upheld by your Server Side dialect/system.