因此,作为一个项目,我被要求使用 Angular 制作一个小型应用程序。对于本地存储,我想使用单独的 js 作为服务。
我想做的是使用 Controller 页面让 html 页面能够使用该服务调用本地存储。原因是我想从多个 html 页面访问本地存储。
我在下面发布了我的代码,非常感谢您的帮助。
配置文件 Controller :
app.controller("ProfileController", function($scope, DataService) {
$scope.profile = DataService.getProfile();
});
个人资料html:
<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;
}
});
最佳答案
上面的代码有一些错误,
(i)您需要将 DataService 注入(inject)到 Controller 中。
(ii) 您可以直接返回配置文件,而不使用 $scope
app.service("DataService", function() {
console.log("DataService");
var localProfile = JSON.parse(localStorage.getItem("profile"));
var profiles = JSON.parse(localStorage.getItem("profile"));
if (localProfile != undefined && localProfile.length > 0) {
this.profiles = localProfile;
} else {
this.profiles = [{
id: "1526",
username: "berserk",
password: "berserk",
age: "31"
}, {
id: "1358",
username: "Johnathan",
password: "test",
age: "17"
}, {
id: "2539",
username: "Britney",
password: "test",
age: "18"
}, {
id: "1486",
username: "Kevin",
password: "test",
age: "7"
}];
}
this.getProfile = function() {
return this.profiles;
}
});
<强> DEMO
关于javascript - 本地存储的 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43157757/