如何使用 Angularjs 在本地存储中存储数据? [英] How do I store data in local storage using Angularjs?

查看:33
本文介绍了如何使用 Angularjs 在本地存储中存储数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用一个服务来执行一个操作,即从服务器检索数据,然后将数据存储在服务器本身上.

Currently I am using a service to perform an action, namely retrieve data from the server and then store the data on the server itself.

相反,我想将数据放入本地存储而不是将其存储在服务器上.我该怎么做?

Instead of this, I want to put the data into local storage instead of storing it on the server. How do I do this?

推荐答案

这是我的一些代码,用于存储和检索到本地存储.我使用广播事件来保存和恢复模型中的值.

this is a bit of my code that stores and retrieves to local storage. i use broadcast events to save and restore the values in the model.

app.factory('userService', ['$rootScope', function ($rootScope) {

    var service = {

        model: {
            name: '',
            email: ''
        },

        SaveState: function () {
            sessionStorage.userService = angular.toJson(service.model);
        },

        RestoreState: function () {
            service.model = angular.fromJson(sessionStorage.userService);
        }
    }

    $rootScope.$on("savestate", service.SaveState);
    $rootScope.$on("restorestate", service.RestoreState);

    return service;
}]);

这篇关于如何使用 Angularjs 在本地存储中存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆