简体   繁体   中英

angularjs localstorage not working properly?

I used local storage. When I go on the page the first time, I am getting an old local storage value. When I refresh I am getting the current value. How can I avoid this error? Every time I only need the current local storage value. I have enclosed this a bit with this code. I have not installed ngstorage. Can someone tell me, whether I need to install ngstorage ?

 .controller('SignInCtrl', [ '$scope','$http' ,'$location','$window', function($scope,$http, $location,$window) { $scope.signin = function() { $http.post('***', userdetails).success(function(data,response) { var nameResponse = JSON.stringify(data.Name); window.localStorage.setItem("name",nameResponse); }) } }]) .controller('MyprofileCtrl', [ '$scope','$http' ,'$location','$window', function($scope,$http, $location,$window) { var name=$window.localStorage.getItem("name"); //console.log(name); if(name == null) { $scope.loginstatus ="Sign Up With Us"; console.log($scope.loginstatus); }else { $scope.loginstatus ='Welcome '+ name.replace(/\\"/g, ""); console.log($scope.loginstatus); } }]) 

Yes your correct you must use ngstorage module.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.7/ngStorage.min.js"></script> </head> <body ng-app="myModule"> <div ng-controller="myCtrl"> <button ng-click="save()">Save</button> <button ng-click="load()">Load</button> <input type="text" ng-model="txt"> {{myData}} </div> </body> <script> var myModule = angular.module("myModule", ["ngStorage"]); myModule.controller("myCtrl", function($scope, $localStorage) { $scope.txt = "prabhu"; $scope.save = function() { alert($scope.txt) $localStorage.message = $scope.txt; } $scope.load = function() { $scope.myData = $localStorage.message; } }); </script> </html> 

No, ngStorage is not required, I hope that the dependency for $window is injected correctly in your controllers.

Try this:

var app = angular.module('your-app', ['the-dependent-modules']);

app.controller('loginPageController', function($window) {
   $window.localStorage.setItem('user-name', 'John');
});

app.controller('myProfilePageController', function($window, $log) {
   var username = $window.localStorage.getItem('user-name');
   $log.debug('username : ' + username);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM