【发布时间】: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