本地存储的角度服务

时间:2017-04-01 13:55:21

标签: javascript angularjs html5 service local-storage

因此,作为一个项目,我被要求使用Angular制作一个小规模的应用程序。对于本地存储,我想使用单独的js作为服务。

我尝试做的是使用控制器页面为html页面提供使用该服务调用localstorage的能力。这是因为我想从多个html页面访问本地存储。

我在下面发布我的代码,非常感谢帮助。

ProfileController可:

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;
  }
});

2 个答案:

答案 0 :(得分:0)

上述代码中的错误很少,

(i)您需要将DataService注入控制器。

(ii)您可以直接返回配置文件,而无需使用$ scope

<html lang="en">

<head>
  <title></title>
  <meta charset="UTF-8" />

</head>

<body>
  <div style="width:500px; background: #cccccc; display: inline-block;">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  </div>
  <img src="https://www.w3schools.com/css/img_fjords.jpg" />
</body>

</html>

<强> DEMO

答案 1 :(得分:0)

我没有看到localStorage的用途,因为你没有初始化它,而是返回初始化的配置文件。除非您通过整个阵列,否则如果您决定添加配置文件,则可能会丢失信息。此外, localProfile 个人资料变量的键也相同,即个人资料