Hi all, This is my first time writing a blog. So please don’t mind small mistakes (if any).
Today we are going to discuss how we can store data locally using $localstorage in AngularJS.
For that you need to follow some pretty easy steps:
Step 1 : Add an HTML file and add following references and code to it,
- <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
• Angular.min.js file
As shown below,
Step 2: Add javascript file and provide its reference in index.html.
Step 3: Add the following code to your javascript file,
- angular.module('app', ['ngStorage']).
-
- controller('Ctrl', function ($scope, $localStorage, $http) {
- if ($localStorage.datastorage) {
- $scope.Applicantdata = $localStorage.datastorage;
- alert("Second Time Call");
- }
- else{
-
- $http.get("http://www.w3schools.com/angular/customers.php").then(function (response) {
- $scope.Applicantdata = response.data.records;
- $localStorage.datastorage = response.data.records;
- alert("First Time Call");
- });
- }
- });
As you can see, when the code will run for the first time it will check the datastorage variable of $localstorage. If datastorage variable has some data then the if part will be executed and it will not hit the server for data. Otherwise else case will be executed and a request will be made to server for the data, also it will store the data in datastorage variable. Once the data is stored in the datastorage variable then there is no need for requesting the server.
Thank You for reading the article – Happy Coding.