[英]Save to and retrieve from local storage with angular
我目前有一个应用程序,用于存储和更新输入字段中的单个值。 但是,我需要它从多个输入中保存,作为一个对象,但我不知道如何执行此操作。 任何有关如何执行此操作的帮助将不胜感激。
我的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");
}
};
}
);
为什么不保存整个对象呢?
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));
};
}
]);
对于集合数据
localStorage.setItem("trip", val);
用于获取数据
localStorage.getItem("trip");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.