【问题标题】:LocalStorageModule in Angular JS to save dataAngular JS中的LocalStorageModule保存数据
【发布时间】:2016-07-28 01:50:24
【问题描述】:

我正在使用 Angular JS 构建一个应用程序,我希望在 localStorage 中持久保存一些特定的数据,以便以后检索它。问题是我在编写代码时遇到了麻烦。当您单击按钮时,我尝试向事件添加更多助手,但检查器总是给出此错误: SyntaxError:位置 0 处 JSON 中的意外标记 u 在 Object.parse(本机)。

我有一个从 app.js 中分离出来的 controller.js,然后我将控制器注入到我的 app.module 中。

如果你能帮助我,那就太好了。提前致谢。

这是给我错误的一段代码:

'use strict';

/* Controllers */

angular.module('Erasmore.controllers', [])
  .controller('Posts', ['$scope', '$http',
    function($scope, $http, localStorageService) {
      $http.get("json/posts.json").success(function(data) {
        $scope.posts = data;
      });

      $scope.assistants = [{
        id: 1,
        name: "James Smith",
        nationality: "English"
      }, {
        id: 3,
        name: "Juan García",
        nationality: "Spanish"
      }, {
        id: 3,
        name: "Eduardo Cruz",
        nationality: "Spanish"
      }, {
        id: 4,
        name: "Jurgen Low",
        nationality: "German"
      }, ];

      var newParticipant = localStorage['assistantList'];
      if (newParticipant !== undefined) {
        $scope.newAssistant = JSON.parse(newParticipant);
      }

      $scope.newAssistant = {};

      $scope.addAssistant = function() {
        $scope.assistants.push($scope.newAssistant);
        $scope.newAssistant = "";
        localStorage['assistantList'] = JSON.stringify($scope.newAssistant);
        console.log(localStorage);
      };

    }
  ])
<div>
  <p>Are you coming?</p>
  <input placeholder="Enter your name" id="name" type="text" class="validate" ng-model="newAssistant.name">
  <input placeholder="Enter your nationality" id="nationality" type="text" class="validate" ng-model="newAssistant.nationality">
  <button class="waves-effect waves-light btn" ng-click="addAssistant()">Confirm</button>
  <button class="waves-effect waves-teal btn-flat modal-trigger">See Assistants</button>
  <ul>
    <li id="asistentes" ng-repeat="assistant in assistants">{{assistant.name}} <span>-</span> {{assistant.nationality}}</li>
  </ul>

【问题讨论】:

  • 'localStorageService' 只需像这样添加您的控制器; .controller('Posts', ['$scope', '$http', 'localStorageService', function($scope, $http, localStorageService) {
  • 是的,我后来意识到了,但它仍然不起作用......

标签: javascript angularjs local-storage angular-local-storage


【解决方案1】:

问题是你没有注入localStorage服务

.controller('Posts', ['$scope', '$http',
function($scope, $http, localStorageService) {

你只注入了 $scope & $http

【讨论】:

  • 是的,我注入了 localStorageService 但也不起作用。控制台给了我同样的错误:
  • SyntaxError: JSON 中位于 Object.parse (native) 位置 0 处的意外标记 u
  • 那是因为您尝试使用 JSON.parse 解析的内容实际上不是有效的 json 对象...例如$scope.newAssistant = ""; 应该是 $scope.newAssistant = {};
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多