【发布时间】:2017-08-26 17:36:09
【问题描述】:
因此,作为一个项目,我被要求使用 Angular 制作一个小型应用程序。对于本地存储,我想使用单独的 js 作为服务。
我想要做的是使用控制器页面让 html 页面能够使用服务调用本地存储。这样做的原因是我想从多个 html 页面访问本地存储。
我在下面发布我的代码,非常感谢您的帮助。
配置文件控制器:
app.controller("ProfileController", function($scope, DataService) {
$scope.profile = DataService.getProfile();
});
profilehtml:
<html>
<head>
<link rel="stylesheet" href="CSS/stylesheet.css">
</head>
<body>
<div class="page">
<h1> Overflow test for longer pages </h1> <br>
<div id = "textholder" ng-repeat="data in profile">
<span>{{data.id}}</span>
</div>
</div>
</body>
服务:
app.service("DataService", function(){
console.log("DataService");
var localProfile = JSON.parse(localStorage.getItem("profile"));
if(localProfile != undefined && localProfile.length>0)
{ this.profiles = localProfile; }
else {
this.profile = [
{ id: "1526", username: "berserk", password: "berserk", age: "31", sex: "male"},
{ id: "1358", username: "Johnathan", password: "test", age: "17", sex: "male"},
{ id: "2539", username: "Britney", password: "test", age: "18", sex: "female"},
{ id: "1486", username: "Kevin", password: "test", age: "7", sex: "male"},
{ id: "7777", username: "jesus", password: "holy", age: "unknown", sex: "male"},
{ id: "6666", username: "satan", password: "hell", age: "unknown", sex: "unknown"}
];
}
this.getProfile = function() {
return this.profile;
}
});
【问题讨论】:
标签: javascript angularjs html service local-storage