Implement Like In Web App With AngularJS And Local Storage

Introduction

Local Storage is the awesome feature of the latest Browsers. The developer can use this feature to store some data into the Browser.

The data can be stored, using Key, value pair in the Local Storage and the value can be accessed, using Key.
 
The syntax to store into Local Storage is given below.
  1. localStorage.setItem(likeKey, likeValue);  
The syntax is given below to access the value from Local Storage.
  1. var voting = localStorage.getItem(likeKey);  
Now, I will implement the code for the storage of Like and accessing.
 
Write the code, given below into controller.

Save Likes.
  1. controller.saveLikes = function (votingId) {  
  2.         var votingKey = votingId;  
  3.         var existingVoting = controller.getLikes(votingId);  
  4.   
  5.         if (existingVoting === 'NaN' || existingVoting === null) {  
  6.             existingVoting = 0;  
  7.         }  
  8.   
  9.         var vote = parseInt(existingVoting) + 1;  
  10.         localStorage.setItem(votingKey, vote);  
  11.         controller.getLikes(votingId);  
  12.     }  
Access Likes from Local Storage.
  1. controller.getLikes = function (votingId) {  
  2.        var votingKey = votingId;  
  3.        controller.getTotalLikes();  
  4.        var voting = localStorage.getItem(votingKey);  
  5.   
  6.        if (voting === 'NaN' || voting === null)  
  7.            return 0;  
  8.   
  9.        return voting;  
  10.    }  
Get Total Likes from Local Storage:
  1. controller.getTotalLikes = function () {  
  2.        controller.totalLikes = 0;  
  3.   
  4.        for (var i = 0; i < localStorage.length; i++) {  
  5.            controller.totalLikes = controller.totalLikes + parseInt(localStorage.getItem(localStorage.key(i)));  
  6.        }  
  7.    }  
Add the link, given below into index.html page. It will provide the URL, given below.
  1. <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">  
Now, call method into HTML partial page, as given below.
  1. <div class="pull-right table-bordered" 
  2. ng-click="homeController.saveLikes(nitroItem.name)" style="cursor: pointer;width:50px; height:40px; background-color:#ededed;">  
  3.                            <div style="margin-top:8px; margin-left:8px;"><i class="fa fa-thumbs-o-up"></i> {{homeController.getLikes(nitroItem.name)}}</div>  
  4.                        </div>  
Output

 

Conclusion

Local Storage provides the best way to store the data up to the local level. You can store the different types of data such as like counts, your wishlist, configuration settings etc.
Next Recommended Reading Deploy AngularJS Web App With Node.js