0

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

我有一个与 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>

4

1 回答 1

0

问题是你没有注入 localStorage 服务

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

你只注入了 $scope & $http

于 2016-07-27T16:32:45.737 回答