我正在使用Angular JS构建一个应用程序,我想在localStorage中保留一些特定的数据,以便以后检索它。问题是我遇到了代码来解决这个问题。我在点击按钮时尝试为事件添加更多助手,但Inspector总是会出现此错误: SyntaxError:位于0的JSON中的意外标记u 在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>
答案 0 :(得分:0)
问题是你没有注入localStorage服务
.controller('Posts', ['$scope', '$http',
function($scope, $http, localStorageService) {
你只注射了$ scope&amp; $ HTTP