使用angular保存到本地存储并从中检索

时间:2017-04-20 12:37:20

标签: javascript angularjs local-storage

我目前有一个应用程序,用于存储和更新输入字段中的单个值。但是,我需要它从多个输入中保存,作为一个对象我猜,但我不知道如何做到这一点。任何有关如何做到这一点的帮助将不胜感激。

我的HTML:

<div ng-controller="newtripController as d">
    <input ng-model="d.startKm" value={{d.startKm}}/>
    <input ng-model="d.stopKm" value={{d.stopkm}}/>
    <input type="button" value="update" ng-click="d.update(d.startKm)" />
</div>

我的控制器:

angular.module("app").controller("newtripController",
    [
        "newtripService",function (newtripService){
            this.startKm = newtripService.getData();
            this.latestData = function(){
                return newtripService.getData();
            };
        this.update = function(val){
            return newtripService.setData(val);
            };
        }
    ]);

我的服务:

angular.module("app").factory("newtripService",
    function($window, $rootScope){
        angular.element($window).on("storage",
            function(event) {
                if(event.key === "trip") {
                    $rootScope.$apply();
                }
            });
        return {
            setData: function(val) {
                localStorage.setItem("trip", val);
                return this;
            },
            getData: function() {
                return localStorage.getItem("trip");
            }
        };
    }
);

2 个答案:

答案 0 :(得分:1)

为什么不保存整个物体?

angular.module('app').controller('newtripController',
[
    'newtripService',function (newtripService){
        this.trip = newtripService.getData();
    this.update = function(val){
        return newtripService.setData(this.trip);
        };
    }
]);

<div ng-controller="newtripController as d">
    <input ng-model="d.trip.startKm" value={{d.trip.startKm}}/>
    <input ng-model="d.trip.stopKm" value={{d.trip.stopkm}}/>
    <input type="button" value="update" ng-click="d.update()" />
<div>

我还没有对此进行测试,因此不确定它是否可以直接运行,您可能需要在保存对象之前对其进行字符串化,然后json在您检索它时对其进行解析。那看起来像是:

 angular.module('app').controller('newtripController',
[
    'newtripService',function (newtripService){
        this.trip = JSON.parse(newtripService.getData());
    this.update = function(val){
        return newtripService.setData(JSON.stringify(this.trip));
        };
    }
]);

答案 1 :(得分:0)

对于设置数据

localStorage.setItem("trip", val);

获取数据

localStorage.getItem("trip"); 
相关问题