我一直在尝试使用ngStorage在我一直在努力的AngularJS应用程序中实现localstorage。调试我一直在查找数据类型问题和错误,即使所有内容都是固定的。
这是插件: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));
};
});
问题的任何解决方案和问题的解释?
答案 0 :(得分:1)
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']);
检查示例Here
答案 1 :(得分:0)
使用$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. :)"}];
});
你确实遇到了一些关于plunkr的小问题(系链没有链接,错误的加载库序列(bootstrap / jQuery)),但主要问题是使用localStorage服务。
查看我的plunker中的更正:http://plnkr.co/edit/K6EKlv1LvJOzKTQo154O?p=preview