我想保存$localStorage
中的所有对象,如下所示:
$localStorage.userData.currentUser = data.name;
$localStorage.userData.devId= data.id;
$localStorage.userData.userRole = data.roles[0].name;
$localStorage.userData.userId = data.user_id;
控制器代码:
myApp.controller('loginController', ['$rootScope', '$scope', 'Auth', '$state', '$localStorage',
function ($rootScope, $scope, Auth, $state, $localStorage) {
function successAuth(res) {
$localStorage.token = res;
$scope.currentUser = $localStorage.token.name;
console.log("res: ", res);
Auth.setUserData(res, function(){
$scope.error = 'No User data available';
});
if ($localStorage.token) {
$state.go("dashboard");
$scope.isLogin = true;
} else {
alert("Invalid username or password");
}
}
$scope.signin = function () {
var formData = {device_id: myip, platform: "WEB", provider: "EMAIL", uid: $scope.login.username, access_token: "", password: $scope.login.password};
Auth.signin(formData, successAuth, function () {
$rootScope.error = 'Invalid credentials';
console.log($rootScope.error);
});
};
$scope.isLogin = !angular.isUndefined($localStorage.token);
}]);
我根据docs尝试了以下操作,但没有奏效。它的错误是'$ storage'未定义
$scope.$storage = $localStorage;
$storage.userData.currentUser = data.name;
$storage.userData.devId= data.id;
$storage.userData.userRole = data.roles[0].name;
$storage.userData.userId = data.user_id;
如何将所有数据保存到$localStorage
,如上所述?
答案 0 :(得分:2)
您可以尝试类似
的内容var newData = {
currentUser : data.name,
devId : data.id,
userRole : data.roles[0].name,
userId : data.user_id
};
localStorage.setItem( 'data' , JSON.stringify(newData) );
可以解析 //对于本地存储中的每个项目......
for( item in localStorage ) {
// Parse the JSON string and add to to array
var newItem = JSON.parse( localStorage[item] );
$scope.data.push( newItem );
}
通过密钥获取数据
localStorage.getItem( 'data' );
答案 1 :(得分:0)
这是我的代码,试试这个:
localStorage.setItem('user', JSON.stringify({
name: "xyz",
age: 25,
comp: "abc"
}));
user = JSON.parse(localStorage.getItem('user'));
console.log(localStorage)

答案 2 :(得分:0)
在loginController
中,注入$window
代替$localStorage
并使用$window.localStorage.getItem(...)
甚至$window.localStorage["storage_name"]
。
要在localStorage
中存储/设置数据,您可以执行$window.localStorage['storage_name'] = angular.toJson( object_to_store)
;