我想将所有对象保存在$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中?

最佳答案

您可以尝试类似

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' );

09-25 18:36