我一直在尝试使用我一直在研究的这个angularjs应用中实现localstorage。调试我,即使一切都固定了,我都会继续查找数据类型问题和错误。
这是plunk:http://plnkr.co/edit/ippdb4
// app.js
var app = angular.module('noteMate', ['ngRoute']);
app.controller('MainCtrl', function($scope, Notes) {
$scope.notes = Notes.entries;
$scope.tempNote = {};
var index;
$scope.save = function() {
Notes.save($scope.tempNote);
$scope.clear();
};
$scope.del = function(idx) {
Notes.del(idx);
};
$scope.edit = function(idx) {
$scope.tempNote = angular.copy($scope.notes[idx]);
index = idx;
};
$scope.clear = function() {
$scope.tempNote = {};
};
$scope.saveEdit = function() {
$scope.notes[index] = $scope.tempNote;
};
$scope.mouse = false;
});
app.service('Notes', function(){
this.saved = $localStorage.getItem('notes');
this.entries = ($localStorage.getItem('notes')!==null) ? JSON.parse(this.saved) :
[{title: "Hey", desc: "This is a sample note. Add your own note by clicking the button below. :)"}];
$localStorage.setItem('notes',JSON.stringify(this.entries));
this.save = function(entry) {
this.entries.push(entry);
$localStorage.setItem('notes',JSON.stringify(this.entries));
};
this.del = function(idx) {
this.entries.splice(idx, 1);
$localStorage.setItem('notes',JSON.stringify(this.entries));
};
});
关于问题的任何解决方案和解释?
1)放置链接
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
2)需要ngStorage
进行注入
var app = angular.module('noteMate', ['ngRoute','ngStorage']);
在此处检查示例
使用$localStorage
服务时,您首先必须自己定义该服务,或者从其他地方(即模块)获取它。
我建议您查看这一点:https://github.com/gsklee/ngstorage
然后重组您的代码看起来像这样:
app.service('Notes', function($localStorage){
this.$storage = $localStorage;
this.saved = $localStorage.notes;
this.entries = ($localStorage.notes!==null) ? JSON.parse(this.saved) :
[{title: "Hey", desc: "This is a sample note. Add your own note by clicking the button below. :)"}];
});
您确实有一些小问题(未链接,错误的加载库序列(bootstrap/jquery)),但主要问题是使用LocalStorage服务。
请查看我的plunker中的更正:http://plnkr.co/edit/k6eklv1lvjozktqo154o?p=preview